蓝易云 - springboot之RedisTemplate的访问单机,哨兵,集群模式

Spring Boot中的RedisTemplate可以用于访问Redis,支持单机、哨兵和集群模式的配置。

  1. 单机模式:
    在Spring Boot中配置RedisTemplate以连接到单机Redis实例很简单。需要配置Redis的主机和端口,示例如下:

    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisConnectionFactory redisConnectionFactory() {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("localhost", 6379);
            return new LettuceConnectionFactory(config);
        }
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory());
            // 配置序列化方式等其他参数
            return template;
        }
    }
    
  2. 哨兵模式:
    哨兵模式是为了增加Redis的高可用性。配置RedisTemplate连接到Redis哨兵集群需要指定哨兵节点的地址和主服务器名称,示例如下:

    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisConnectionFactory redisConnectionFactory() {
            RedisSentinelConfiguration config = new RedisSentinelConfiguration()
                .master("mymaster")
                .sentinel("host1", 26379)
                .sentinel("host2", 26379)
                .sentinel("host3", 26379);
            return new LettuceConnectionFactory(config);
        }
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory());
            // 配置序列化方式等其他参数
            return template;
        }
    }
    
  3. 集群模式:
    Redis集群模式将数据分散在多个节点上,配置RedisTemplate连接到Redis集群需要指定集群节点的地址,示例如下:

    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisConnectionFactory redisConnectionFactory() {
            RedisClusterConfiguration config = new RedisClusterConfiguration()
                .addClusterNode(new RedisNode("host1", 6379))
                .addClusterNode(new RedisNode("host2", 6379))
                .addClusterNode(new RedisNode("host3", 6379));
            return new LettuceConnectionFactory(config);
        }
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory());
            // 配置序列化方式等其他参数
            return template;
        }
    }
    

以上是配置RedisTemplate以连接到单机、哨兵和集群模式的示例。在实际应用中,还可以根据需求配置连接池、序列化方式、超时等其他参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值