spring boot以lettuce连接池整合redis-cluster(单机及集群版)

一.添加相关pom依赖
commons依赖主要应用于单机版

<!--redis-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redis依赖commons-pool 这个依赖一定要添加 -->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-pool2</artifactId>
</dependency>


二.修改application.yml
a. 单机版:

#redis单机版
  redis:
     host: 192.168.40.156
     port: 6379
      # 密码 没有则可以不填
   password: 123456
      # 如果使用的jedis 则将lettuce改成jedis即可
   lettuce:
        pool:
          # 最大活跃链接数 默认8(使用负值表示没有限制)
         max-active: 8
          
在使用 `spring-boot-starter-data-redis` 连接 Redis 集群时,配置方式需要根据实际使用的 Spring Boot 本进行调整。对于 Spring Boot 2.x 本,其默认使用的是 Lettuce 作为 Redis 客户端,支持连接 Redis 集群模式。 ### 配置 Redis 集群连接 在 `application.yml` 文件中,可以按照如下方式配置 Redis 集群连接: ```yaml spring: redis: cluster: nodes: - 172.4.2.65:30001 - 172.4.2.65:30002 - 172.4.2.65:30003 - 172.4.2.65:30004 - 172.4.2.65:30005 - 172.4.2.65:30006 password: test@123 timeout: 6000ms lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: 2000ms ``` #### 配置说明: - `cluster.nodes`:定义了 Redis 集群的节点列表,格式为 `host:port`,支持多个节点配置。 - `password`:集群连接所需的密码,如果 Redis 集群启用了认证机制,则必须配置。 - `timeout`:设置连接超时时间,单位为毫秒或时间单位(如 `6000ms`)。 - `lettuce.pool`:Lettuce 客户端的连接池配置,用于控制连接资源的使用。 ### 使用 `RedisConnectionFactory` 在代码中,可以通过注入 `RedisConnectionFactory` 来创建 `RedisTemplate` 或 `StringRedisTemplate` 实例,进而操作 Redis 数据库。 ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` ### 客户端选择:Lettuce vs Jedis Spring Boot 2.x 默认使用 Lettuce 作为 Redis 客户端,相比 Jedis,Lettuce 具有以下优势: - **线程安全**:Lettuce 的连接是线程安全的,可以在多个线程之间共享使用,而 Jedis 的连接不是线程安全的,通常需要配合连接池使用。 - **支持异步操作**:Lettuce 提供了对异步操作的支持,适合高并发场景[^1]。 ### 集群模式下的重定向处理 Redis 集群模式下,客户端请求可能会被重定向到其他节点。Spring Boot 提供了 `max-redirects` 参数来控制最大重定向次数,避免因多次重定向导致性能下降或请求失败。 ```yaml spring: redis: cluster: max-redirects: 5 ``` 该配置表示在集群模式下,客户端最多允许被重定向 5 次。超过该次数后,客户端将抛出异常[^2]。 --- ### 相关问题 1. 如何在 Spring Boot 中使用 Jedis 连接 Redis 集群? 2. Spring Boot 2.x 和 1.5.x 在 Redis 集群配置上有何区别? 3. Redis 集群模式下如何实现连接池配置? 4. RedisTemplate 和 StringRedisTemplate 有何区别? 5. 如何在 Spring Boot 中实现 Redis 的哨兵模式配置?
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hello_world!

你的鼓励将是我创作的最大动力!

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

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

打赏作者

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

抵扣说明:

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

余额充值