Spring Data Redis 使用Lettuce在Redis集群中无法高可用
Spring boot 2.1.X 下Spring-data-redis-start 使用 Lettuce 作为Redis连接池
问题场景
在App运行期间Redis集群中某个Master节点 Shutdown,导致应用连接Redis报错,错误信息 连接超时。
解决方案
Lettuce 解决方法
使用 RedisClusterClient.reloadPartitions 自动reload pattitions。
Spring-data-redis 解决方法
重写 RedisConnectionFactory Bean
@Data
@Component
public class RedisConfig {
@Autowired
RedisProperties redisProperties;
@Bean
public RedisConnectionFactory newLettuceConnectionFactory() {
ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
.enablePeriodicRefresh(Duration.ofSeconds(30))
.enableAllAdaptiveRefreshTriggers()
.build();
ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
.validateClusterNodeMembership(false)
.topologyRefreshOptions(clusterTopologyRefreshOptions)
.build();
LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
.commandTimeout(redisProperties.getTimeout())
.shutdownTimeout(Duration.ZERO)
.clientOptions(clusterClientOptions)
.build();
RedisClusterConfiguration serverConfig = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
return new LettuceConnectionFactory(serverConfig, clientConfig);
}
}
使用jedis 替换 lettuce
pom 信息
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
lettuce 配置信息
spring.redis.lettuce.pool.max-active=10
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-wait=10
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.shutdown-timeout=1S
jedis 配置信息
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.max-idle=10
spring.redis.jedis.pool.max-wait=10
spring.redis.jedis.pool.min-idle=5
来源:oschina
链接:https://my.oschina.net/u/2257885/blog/3135417