• Springboot集成redis--不同环境切换


    1.单机配置
    spring:
      redis:
        mode: singleton
        host: 127.0.0.1
        port: 6379
        lettuce:
          pool:
            max-active: 8   #连接池最大阻塞等待时间(使用负值表示没有限制
            max-idle: 2     #连接池中的最大空闲连接
            min-idle: 1     #连接池最大阻塞等待时间(使用负值表示没有限制
        password: 123456
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    2.集群配置
    spring:
      redis:
        cluster:
          nodes: 192.168.68.152:7000,192.168.68.152:7001,192.168.68.152:7002,192.168.68.152:7003,192.168.68.152:7004,192.168.68.152:7005
        lettuce:
          pool:
            max-active: 8   #连接池最大阻塞等待时间(使用负值表示没有限制
            max-idle: 2     #连接池中的最大空闲连接
            min-idle: 1     #连接池最大阻塞等待时间(使用负值表示没有限制
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    3.配置文件编写
    package com.example.demo.config;
    
    import io.lettuce.core.ReadFrom;
    import io.lettuce.core.cluster.ClusterClientOptions;
    import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
    import lombok.AllArgsConstructor;
    import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.autoconfigure.AutoConfigureBefore;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
    import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.*;
    import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
    import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
    import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    import javax.annotation.Resource;
    import java.time.Duration;
    import java.util.ArrayList;
    import java.util.List;
    /**
     * @author fuhao
     * @create 2023-09-07 15:42
     **/
    @Configuration
    @AllArgsConstructor
    @AutoConfigureBefore(RedisAutoConfiguration.class)
    public class RedisConfig {
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate(@Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    
            //设置value的序列化器
            GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
            redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
            redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            return redisTemplate;
        }
        @Resource
        RedisProperties redisProperties;
    
        @Bean
        public GenericObjectPoolConfig poolConfig() {
            GenericObjectPoolConfig config = new GenericObjectPoolConfig();
            config.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
            config.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
            config.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
            config.setMaxWaitMillis(redisProperties.getLettuce().getPool().getMaxWait().toMillis());
            return config;
        }
    
    
        /**
         * sentinel 哨兵模式configuration
         *
         * */
        @Bean
        @ConditionalOnProperty(value = "spring.redis.mode",havingValue = "sentinel")
        public RedisSentinelConfiguration redisConfigurationModeSentinel() {
            RedisSentinelConfiguration redisConfig = new RedisSentinelConfiguration();
            redisConfig.setMaster(redisProperties.getSentinel().getMaster());
            if(redisProperties.getSentinel().getNodes()!=null) {
                List<RedisNode> sentinelNode=new ArrayList<RedisNode>();
                for(String sen : redisProperties.getSentinel().getNodes()) {
                    String[] arr = sen.split(":");
                    sentinelNode.add(new RedisNode(arr[0],Integer.parseInt(arr[1])));
                }
                redisConfig.setDatabase(redisProperties.getDatabase());
                redisConfig.setPassword(redisProperties.getPassword());
                redisConfig.setSentinelPassword(redisConfig.getPassword());
                redisConfig.setSentinels(sentinelNode);
            }
            return redisConfig;
        }
    
        /**
         * singleten单机 模式configuration
         *
         * */
        @Bean
        @ConditionalOnProperty(value = "spring.redis.mode",havingValue = "singleton")
        public RedisStandaloneConfiguration redisConfigurationModeSingleton() {
    
            RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration();
            standaloneConfiguration.setDatabase(redisProperties.getDatabase());
            standaloneConfiguration.setHostName(redisProperties.getHost());
            standaloneConfiguration.setPassword(redisProperties.getPassword());
            standaloneConfiguration.setPort(redisProperties.getPort());
            return standaloneConfiguration;
        }
    
        /**
         * cluster 模式configuration
         *
         * */
        @Bean
        @ConditionalOnProperty(value = "spring.redis.mode",havingValue = "cluster")
        public RedisClusterConfiguration redisClusterConfigurationModeCluster() {
    
            RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
            redisClusterConfiguration.setPassword(redisProperties.getPassword());
            return redisClusterConfiguration;
        }
    
        /**
         * singleton单机 模式redisConnectionFactory
         *
         */
        @Bean("redisConnectionFactory")
        @ConditionalOnProperty(value = "spring.redis.mode",havingValue = "singleton")
        public LettuceConnectionFactory redisConnectionFactoryModeSingleton(@Qualifier("poolConfig") GenericObjectPoolConfig config,
                RedisStandaloneConfiguration redisStandaloneConfiguration) {//注意传入的对象名和类型RedisSentinelConfiguration
            LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(config).build();
            return new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfiguration);
        }
    
    
        /**
         * sentinel哨兵 模式redisConnectionFactory
         *
         */
        @Bean("redisConnectionFactory")
        @ConditionalOnProperty(value = "spring.redis.mode",havingValue = "sentinel")
        public LettuceConnectionFactory redisConnectionFactoryModeSentinel(@Qualifier("poolConfig") GenericObjectPoolConfig config,
                RedisSentinelConfiguration redisConfig) {//注意传入的对象名和类型RedisSentinelConfiguration
            LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(config).build();
            return new LettuceConnectionFactory(redisConfig, clientConfiguration);
        }
    
    
        /**
         * cluster 模式redisConnectionFactory
         *
         */
        @Bean("redisConnectionFactory")
        @ConditionalOnProperty(value = "spring.redis.mode",havingValue = "cluster")
        public LettuceConnectionFactory redisConnectionFactory(RedisClusterConfiguration redisClusterConfiguration) {
    
            ClusterTopologyRefreshOptions clusterTopologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                    .enablePeriodicRefresh()
                    .enableAllAdaptiveRefreshTriggers()
                    .refreshPeriod(Duration.ofSeconds(5))
                    .build();
            ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
                    .topologyRefreshOptions(clusterTopologyRefreshOptions).build();
            LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder()
                    .readFrom(ReadFrom.REPLICA_PREFERRED)
                    .clientOptions(clusterClientOptions).build();
            return new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration);
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    4.pom.xml
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>fastjsonartifactId>
      <version>2.0.37version>
    dependency>
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-pool2artifactId>
      <version>2.11.1version>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-data-redisartifactId>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-webartifactId>
    dependency>
    
    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
  • 相关阅读:
    提示工程(Prompt Engineering)指南(入门篇)
    J2EE从入门到入土07.XML建模
    实现一个todoList可直接操作数据(上移、下移、置顶、置底)
    Python - 实现渐变色的RGB计算
    基于ssm的教资考前指导系统设计与实现-计算机毕业设计源码+LW文档
    C语言基础算法复习
    浅谈安科瑞无线测温设备在挪威某项目的应用
    做直播或短视频 其实有几个精准粉丝就可以很快变现
    世界杯的“中国元素”昂扬大国担当,点面科技全新推出的多模态多功能移动终端踏上卡塔尔征途!
    Linux之进程创建及退出
  • 原文地址:https://blog.csdn.net/Nice_EveryDay/article/details/132743642