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


香港五网CN2网络云服务器链接:www.tsyvps.com

蓝易云香港五网CN2 GIA/GT精品网络服务器。拒绝绕路,拒绝不稳定。

蓝易云是一家专注于香港及国内数据中心服务的提供商,提供高质量的服务器租用和云计算服务、包括免备案香港服务器、香港CN2、美国服务器、海外高防服务器、国内高防服务器、香港VPS等。致力于为用户提供稳定,快速的网络连接和优质的客户体验。
最后修改:2023 年 08 月 24 日
如果觉得我的文章对你有用,请随意赞赏