卡飞资源网

专业编程技术资源共享平台

后端开发必看!Spring Boot 3 连接 Redis 的三种客户端!

最近和不少在互联网大厂做后端开发的朋友聊天,发现大家在使用 Spring Boot 3 连接 Redis 时,总会遇到各种各样的问题。有的说项目上线后 Redis 连接频繁超时,有的吐槽性能不如预期,还有人因为客户端选择不当导致系统稳定性出问题。其实,这些问题很大程度上和没有选对 Spring Boot 3 连接 Redis 的客户端有关!今天就来和大家聊聊 Spring Boot 3 中连接 Redis 的三种客户端,帮你彻底解决这些困扰。

背景介绍

随着互联网业务的快速发展,数据缓存、高并发读写需求越来越普遍,Redis 凭借其高性能、丰富的数据结构,成为后端开发中不可或缺的组件。而 Spring Boot 作为 Java 后端开发的热门框架,其与 Redis 的集成也在不断升级。到了 Spring Boot 3 版本,官方支持了 Jedis、Lettuce、Redisson 三种主流客户端,每种客户端都有其独特的特性和适用场景。

Jedis 是 Redis 的老牌 Java 客户端,它的 API 设计和 Redis 命令基本保持一致,使用起来非常直观,开发者可以轻松上手。但是,Jedis 基于阻塞 I/O,在高并发场景下可能会出现性能瓶颈。

Lettuce 则是基于 Netty 框架实现的异步、事件驱动的 Redis 客户端。它采用非阻塞 I/O,支持异步操作,能够很好地应对高并发场景,并且线程安全,多个线程可以共享一个连接实例,在资源利用上更加高效,也是 Spring Boot 3 默认使用的 Redis 客户端。

Redisson 与前两者不同,它不仅仅是一个 Redis 客户端,更是一个在 Redis 基础上实现的 Java 驻内存数据网格客户端。Redisson 提供了分布式锁、分布式集合、分布式对象等丰富的高级功能,极大地简化了分布式系统的开发。

Jedis 客户端

如果你的项目并发量不高,对分布式功能需求较少,且更倾向于使用传统、简单直接的 API,那么 Jedis 是个不错的选择。在 Spring Boot 3 项目中使用 Jedis,首先需要在pom.xml中添加依赖:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

然后在配置文件application.yml中配置 Redis 连接信息:

spring:
  redis:
    host: localhost
    port: 6379
    jedis:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0

在代码中,通过JedisConnectionFactory获取连接进行操作:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

Lettuce 客户端

当你的项目面临高并发场景,需要高效的异步操作时,Lettuce 无疑是最佳选择。在pom.xml中添加 Lettuce 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml配置与 Jedis 类似:

spring:
  redis:
    host: localhost
    port: 6379
    lettuce:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0

Spring Boot 3 默认会自动配置 Lettuce 连接工厂和 RedisTemplate,无需过多手动配置,直接注入RedisTemplate即可使用:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/redis")
    public String redisTest() {
        redisTemplate.opsForValue().set("key", "value");
        return redisTemplate.opsForValue().get("key").toString();
    }
}

Redisson 客户端

如果你的项目需要使用 Redis 的高级分布式功能,比如分布式锁、分布式缓存等,Redisson 绝对能让你事半功倍。添加 Redisson 依赖:

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.16.1</version>
</dependency>

在application.yml中配置 Redis 连接信息:

spring:
  redis:
    host: localhost
    port: 6379

Redisson 的配置更加简单,通过RedissonClient即可操作 Redis,以下是使用 Redisson 实现分布式锁的示例:

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/lock")
    public String lockTest() {
        RLock lock = redissonClient.getLock("myLock");
        try {
            // 尝试加锁,最多等待100秒,上锁以后10秒自动解锁
            boolean isLocked = lock.tryLock(100, 10, TimeUnit.SECONDS);
            if (isLocked) {
                // 执行业务逻辑
                return "获取锁成功,执行业务逻辑";
            } else {
                return "获取锁失败";
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return "加锁过程中发生异常";
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}

总结

在 Spring Boot 3 项目中连接 Redis,选择合适的客户端至关重要。如果你追求简单易用,Jedis 是首选;面对高并发场景,Lettuce 能为你保驾护航;而需要高级分布式功能时,Redisson 则是最佳伙伴。

希望今天的分享能帮助大家解决 Redis 连接的难题!如果你在实际开发中遇到其他问题,或者有更好的实践经验,欢迎在评论区留言交流。觉得文章有用的话,别忘了点赞、收藏和转发,让更多后端开发的小伙伴少踩坑!

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言