SpringBoot Redis入门(一)——redis、Lettuce、Redisson使用

  • 本章:将展示SpringBoot集成Redis三种客户端的配置要点和常见应用示例;
  • 下章:自行实现一个方法级的缓存注解,简化版的Cacheable,使初学者加深对Spring缓存框架的理解。

一、Lettuce客户端

Lettuce 是一种可扩展的、线程安全的 Redis 高级客户端。
从 Spring Boot 2.x 开始, Lettuce 已取代 Jedis 成为SpringBoot 默认的 Redis 客户端。

  • 相比于 Jedis,Lettuce更加全面,并且解决了 Jedis 客户端实例存在非线程安全的问题
  • 支持同步编程,异步编程,响应式编程,自动重新连接,主从模式,集群模块,哨兵模式,管道和编码器等等高级的 Redis 特性
  • Lettuce 底层基于 Netty 框架的事件驱动与 redis 通信,采用了非阻塞的 I/O 操作,可异步调用,相比 Jedis,性能高
  • Lettuce 的 API 是线程安全的,如果不是执行阻塞和事务操作,如 BLPOP 和MULTI/EXEC 等命令,多个线程就可以共享一个连接,性能方面不会衰减。

1.1 pom.xml引入依赖

	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> 
    </parent>
    
<dependencies>
        <!-- redis 缓存操作  默认使用 Lettuce 客户端-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- pool 对象池 Lettuce客户端依赖的插件-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

        <!-- 阿里JSON解析器 -->
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.34</version>
        </dependency>

        <!-- 方便等会写单元测试 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

1.2 application.yml

配置redis服务器配置

spring:
    redis:
        # 地址
        host: localhost
        # 端口,默认为6379
        port: 6379
        # 数据库索引
        database: 0
        # 密码
        password: 123456
        # 连接超时时间
        timeout: 10s
        lettuce:
            pool:
                # 连接池中的最小空闲连接
                min-idle: 0
                # 连接池中的最大空闲连接
                max-idle: 8
                # 连接池的最大数据库连接数
                max-active: 8
                # #连接池最大阻塞等待时间(使用负值表示没有限制)
                max-wait: -1ms

1.3 redis缓存应用

UserService.java

@Service
public class UserService {
   
   

	//由于引入redis-starter包,spring已经完成了RedisTemplate 对象创建,什么都不用做就可以直接使用了。
    @Autowired
    RedisTemplate redisTemplate;

	/**
     * 最简单的使用,通过key-value方式存取变量;
     * @param username
     * @return
     */
    public Object getUserInfo(String username) {
   
   
    	//通过用户名从缓存获取用户信息,如果没有即新建并存缓存起来;
        if (redisTemplate.opsForValue().get(username) == null) {
   
   
            System.out.println("未获取到缓存,新建用户信息.............");
            Map<String, Object> user = new HashMap<>()
### Spring Boot 使用 Redisson 连接和管理 Redis 集群 #### 1. 添加依赖项 为了在 Spring Boot使用 Redisson 来连接和管理 Redis 集群,首先需要引入相应的 Maven 或 Gradle 依赖。 对于 Maven 用户: ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.20.0</version> </dependency> ``` 对于 Gradle 用户: ```groovy implementation 'org.redisson:redisson-spring-boot-starter:3.20.0' ``` 此版本兼容最新的 Spring BootRedis 版本[^1]。 #### 2. 配置 `application.yml` 文件 编辑项目的 `application.yml` 文件来定义 Redisson 客户端配置参数。下面是个典型的例子,展示了如何设置单个节点或多个节点组成的集群模式下的连接属性。 ```yaml spring: redis: database: 0 timeout: 2000 lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 # Redisson specific properties redisson: single-server-address: "redis://127.0.0.1:6379" # For cluster mode uncomment below lines and comment out the above line. # cluster-mode-enabled: true # cluster-nodes: ["redis://127.0.0.1:7000", "redis://127.0.0.1:7001"] ``` 当启用集群模式时,通过指定组地址列表可以实现高可用性和负载均衡功能[^2]。 #### 3. 初始化并注入 RedissonClient 实例 可以通过自动装配的方式获取已经由 spring boot starter 创建好的 `RedissonClient` 对象实例,在任何组件中都可以方便地调用它来进行各种数据结构的操作。 ```java @Autowired private RedissonClient redisson; ``` #### 4. 编写业务逻辑代码 利用获得的 `RedissonClient` 可以轻松访问分布式锁、队列以及其他高级特性。这里给出段简单示例程序片段说明如何向 Redis 存储键值对以及读取它们。 ```java public void setKeyValue(String key, String value){ RBucket<String> bucket = redisson.getBucket(key); bucket.set(value); } public String getKeyValue(String key){ RBucket<String> bucket = redisson.getBucket(key); return bucket.get(); } ``` 上述方法分别实现了基本的数据存入与取出操作,实际应用中还可以基于需求扩展更多复杂的功能模块[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wolf犭良

谢谢您的阅读与鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值