【实践篇】4.13 SpringBoot Redis 多数据源集成支持哨兵模式和Cluster集群模式
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.HashSet;
import java.util.Set;
@Configuration
public class RedisConfig {
// 提供一个默认的RedisTemplate
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(lettuceConnectionFactory);
return template;
}
// 提供一个StringRedisTemplate
@Bean
public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(lettuceConnectionFactory);
return template;
}
// 当使用Redis哨兵模式时,需要如下配置
@Bean
public LettuceConnectionFactory redisSentinelConnectionFactory() {
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
.master("mymaster")
.sentinel("127.0.0.1", 26379)
.sentinel("127.0.0.1", 26380);
return new LettuceConnectionFactory(sentinelConfig);
}
// 当使用Redis Cluster模式时,需要如下配置
@Bean
public LettuceConnectionFactory redisClusterConnectionFactory() {
Set<String> clusterNodes = new HashSet<>();
clusterNodes.add("127.0.0.1:6379");
clusterNodes.add("127.0.0.1:6380");
clusterNodes.add("127.0.0.1:6381");
RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration(clusterNodes);
return new LettuceConnectionFactory(clusterConfig);
}
}
这个配置类提供了创建多个LettuceConnectionFactory的Bean,分别用于连接Redis的哨兵模式和集群模式。同时,它还提供了两个RedisTemplate的Bean,一个用于Key和Value都是String类型的操作,另一个用于Key是String,Value是Object的操作。这样,开发者可以根据实际需求选择合适的连接方式和操作方式。
评论已关闭