spring boot 微服务 redis集群配置

spring boot 微服务 redis集群配置

1.redis 有三种集群模式  主从模式  哨兵模式(Sentinel)  Cluster模式

引入redis依赖
yaml 复制代码
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
   </dependency>
   <dependency>
       <groupId>io.lettuce.core</groupId>
       <artifactId>lettuce-core</artifactId>
   </dependency>
2.主从模式配置 一般实现redis的读写分离 yaml配置如下
java 复制代码
     spring:
       redis:
         host: 127.0.0.1
         port: 6379
         password: your_password
         lettuce:
           pool:
             max-active: 8
             max-wait: -1
             max-idle: 8
             min-idle: 0
           shutdown-timeout: 100ms
    
2.1 在代码配置redis读写分离
java 复制代码
  @Configuration
     public class RedisConfig {

         @Value("${spring.redis.host}")
         private String redisHost;

         @Value("${spring.redis.port}")
         private int redisPort;

         @Value("${spring.redis.password}")
         private String redisPassword;

         @Bean
         public RedisConnectionFactory masterRedisConnectionFactory() {
             RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort);
             config.setPassword(RedisPassword.of(redisPassword));
             return new LettuceConnectionFactory(config);
         }

         @Bean
         public RedisConnectionFactory slaveRedisConnectionFactory() {
             RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("127.0.0.2", 6380);
             config.setPassword(RedisPassword.of(redisPassword));
             return new LettuceConnectionFactory(config);
         }

         @Bean
         public RedisTemplate<String, Object> masterRedisTemplate(RedisConnectionFactory masterRedisConnectionFactory) {
             RedisTemplate<String, Object> template = new RedisTemplate<>();
             template.setConnectionFactory(masterRedisConnectionFactory);
             template.setKeySerializer(new StringRedisSerializer());
             template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
             return template;
         }

         @Bean
         public RedisTemplate<String, Object> slaveRedisTemplate(RedisConnectionFactory slaveRedisConnectionFactory) {
             RedisTemplate<String, Object> template = new RedisTemplate<>();
             template.setConnectionFactory(slaveRedisConnectionFactory);
             template.setKeySerializer(new StringRedisSerializer());
             template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
             return template;
         }
     }
3. 哨兵模式(Sentinel)yaml配置
java 复制代码
 spring:
     redis:
       cluster:
         nodes: 127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002
       password: your_redis_password
       timeout: 5000ms
3.1 在代码中配置
java 复制代码
   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 org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
   import org.springframework.data.redis.serializer.StringRedisSerializer;

   @Configuration
   public class RedisConfig {

       @Bean
       public RedisClusterConfiguration redisClusterConfiguration() {
           RedisClusterConfiguration configuration = new RedisClusterConfiguration();
           configuration.setClusterNodes(Arrays.asList(
               "127.0.0.1:7000", "127.0.0.1:7001", "127.0.0.1:7002"
           ));
           configuration.setPassword("your_redis_password");
           return configuration;
       }

       @Bean
       public LettuceConnectionFactory lettuceConnectionFactory(RedisClusterConfiguration redisClusterConfiguration) {
           return new LettuceConnectionFactory(redisClusterConfiguration);
       }

       @Bean
       public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
           RedisTemplate<String, Object> template = new RedisTemplate<>();
           template.setConnectionFactory(lettuceConnectionFactory);
           template.setKeySerializer(new StringRedisSerializer());
           template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
           template.setHashKeySerializer(new StringRedisSerializer());
           template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
           return template;
       }
   }
   
4. Cluster模式 yaml 配置如下
yaml 复制代码
     spring:
       redis:
         cluster:
           nodes: 127.0.0.1:7000,127.0.0.2:7001,127.0.0.3:7002,127.0.0.4:7003,127.0.0.5:7004,127.0.0.6:7005
         database: 0
         password: your_password
     
4.1代码配置如下
java 复制代码
   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 org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
   import org.springframework.data.redis.serializer.StringRedisSerializer;

   @Configuration
   public class RedisConfig {

       @Bean
       public RedisClusterConfiguration redisClusterConfiguration() {
           RedisClusterConfiguration configuration = new RedisClusterConfiguration();
           configuration.setClusterNodes(Arrays.asList(
               "127.0.0.1:7000", "127.0.0.1:7001", "127.0.0.1:7002"
           ));
           configuration.setPassword("your_redis_password");
           return configuration;
       }

       @Bean
       public LettuceConnectionFactory lettuceConnectionFactory(RedisClusterConfiguration redisClusterConfiguration) {
           return new LettuceConnectionFactory(redisClusterConfiguration);
       }

       @Bean
       public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
           RedisTemplate<String, Object> template = new RedisTemplate<>();
           template.setConnectionFactory(lettuceConnectionFactory);
           template.setKeySerializer(new StringRedisSerializer());
           template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
           template.setHashKeySerializer(new StringRedisSerializer());
           template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
           return template;
       }
   }
5.如果需要修改redis的键值对 序列化 如下配置
java 复制代码
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

/**
 * @author borui
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;


    public FastJson2JsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
    }
}

@Configuration
@EnableCaching
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
        //JdkSerializationRedisSerializer serializer =new JdkSerializationRedisSerializer();
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer((new StringRedisSerializer()));

        template.afterPropertiesSet();
        return template;
    }
}
相关推荐
冧轩在努力5 小时前
redis的应用--分布式锁
数据库·redis·分布式
2021-5-55 小时前
利用 Redis 与 Lua 脚本解决秒杀系统中的高并发与库存超卖问题
数据库·redis·lua
夏子曦5 小时前
Redis——主从复制原理
数据库·redis·缓存
行思理7 小时前
如何使用brew安装phpredis扩展?
redis·macos·brew·phpredis
ThisIsClark8 小时前
【后端面试总结】Redis过期删除策略
数据库·redis·缓存
清酒伴风(面试准备中......)8 小时前
Redis使用场景-缓存-缓存击穿
java·数据库·redis·缓存·面试·实习
蟹黄堡㋡9 小时前
redis学习1
数据库·redis·学习
诸葛博仌13 小时前
redis签到命令练习
数据库·redis·缓存
.生产的驴13 小时前
SpringBoot 监听Redis键过期事件 过期监听
java·spring boot·redis·后端·spring·spring cloud·微服务