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;
    }
}
相关推荐
tellmewhoisi2 小时前
多版本共用redis的token有效期校验(过期重新登录)
java·redis·缓存
Wzx1980123 小时前
Redis&ES——Retriever的抽象实现
数据库·人工智能·redis·elasticsearch
吴声子夜歌5 小时前
Redis 3.x——哨兵API
redis·sentinel
宠友信息10 小时前
Spring Boot与Redis ZSet实现仿小红书源码双列瀑布流推荐
java·大数据·前端·spring boot·redis·mysql·uni-app
梅头脑10 小时前
Redis 核心原理:为什么快?五种数据结构 + 持久化双引擎
redis
霸道流氓气质10 小时前
CodeBuddy中配置Redis MCP 连接与排错实战
数据库·redis·缓存
数行拙笔10 小时前
Redis---hash类型
数据库·redis·哈希算法
霸道流氓气质12 小时前
Kiro 中配置 Redis MCP Server 完整指南
数据库·redis·缓存
952361 天前
Redis - 应用
数据库·redis·分布式·缓存
青山木1 天前
一把 Redis 分布式锁,踩透四个坑:锁争抢、僵尸锁、锁过期、锁丢失
java·数据库·redis·后端