Appearance
Spring Boot:配置 Redis 集群
Note:基于 Spring Boot 2.7.6 版本。
YAML
spring:
redis:
cluster:
nodes:
- YOUR.HOSTNAME:6371
- YOUR.HOSTNAME:6372
- YOUR.HOSTNAME:6373
- YOUR.HOSTNAME:6374
- YOUR.HOSTNAME:6375
- YOUR.HOSTNAME:6376
max-redirects: 3
lettuce:
cluster:
refresh:
adaptive: true # Proactively refresh the Redis cluster topology
period: 2000
pool:
enabled: true # Ensure connection pooling is enabled
max-active: 16
max-idle: 8
min-idle: 2
max-wait: -1ms
username: YOUR_USERNAME
password: YOUR_PASSWORDSpring Boot 2.7.6 Lettuce 连接池依赖 commons-pool2。当类路径中存在 commons-pool2 时,将自动启用连接池。否则,即使声明了 spring.redis.lettuce.pool.enabled = true 也将在项目运行时引发异常。
XML
<!-- Commons Pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>为了让 Lettuce 客户端在进行读操作时,优先从从节点(Replica)读取数据,而不是从主节点(Master)读取数据,可以自定义 Lettuce 客户端的读取策略:
Java
@Configuration
public class RedisConfiguration {
@Bean
public LettuceClientConfigurationBuilderCustomizer clientConfigurationBuilderCustomizer() {
return builder -> builder.readFrom(ReadFrom.REPLICA_PREFERRED);
}
}1
2
3
4
5
6
7
2
3
4
5
6
7