Spring Boot 整合 Redis 集群详解
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.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.HashSet;
import java.util.Set;
@Configuration
public class RedisClusterConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
Set<String> redisNodes = new HashSet<>();
redisNodes.add("redis://192.168.1.1:6379"); // 添加集群节点
redisNodes.add("redis://192.168.1.2:6379");
// ... 添加更多节点 ...
RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration(redisNodes);
return new LettuceConnectionFactory(clusterConfiguration);
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
return template;
}
}
这段代码演示了如何在Spring Boot应用程序中配置和连接到Redis集群。它使用Lettuce客户端库,通过RedisClusterConfiguration
定义集群节点,并通过LettuceConnectionFactory
创建连接。RedisTemplate
提供了操作Redis的方法,可以用于存储和检索对象。
评论已关闭