springBoot 整合 Redis哨兵/读写分离/Lettuce

pom.xml

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- 提供Redis连接池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

 

配置文件

server:
  port: 9001
spring:
  redis:
#    host: 172.16.180.23 
#    port: 6379
#    database: 0
#    password: ''
    timeout: 6000
    ###################以下为redis哨兵增加的配置###########################
    sentinel:
      nodes: 172.16.180.23:26379,172.16.180.23:26380,172.16.180.23:26381
      master: mymaster
    ###################以下为lettuce连接池增加的配置###########################
    lettuce:
      pool:
        max-active:  100 # 连接池最大连接数(使用负值表示没有限制)
        max-idle: 100 # 连接池中的最大空闲连接
        min-idle: 50 # 连接池中的最小空闲连接
        max-wait: 6000 # 连接池最大阻塞等待时间(使用负值表示没有限制
RedisTemplate配置


@Configuration
@Slf4j
public class RedisConfiguration {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
        //创建Json序列化对象
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 将默认序列化改为Jackson2JsonRedisSerializer序列化
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setKeySerializer(jackson2JsonRedisSerializer);// key序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);// value序列化
        template.setHashKeySerializer(jackson2JsonRedisSerializer);// Hash key序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();
        return template;
    }

}
Redis哨兵配置
@Configuration
@ConfigurationProperties(prefix = "spring.redis.sentinel")
public class RedisSentinelConfig {
    @Value("spring.redis.timeout.sentinel.nodes")
    private Set<String> nodes;
    @Value("spring.redis.timeout.sentinel.master")
    private String master;

    @Value("${spring.redis.timeout}")
    private long timeout;
    //@Value("${spring.redis.password}")
    //private String password;
    @Value("${spring.redis.lettuce.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.lettuce.pool.min-idle}")
    private int minIdle;
    @Value("${spring.redis.lettuce.pool.max-wait}")
    private long maxWait;
    @Value("${spring.redis.lettuce.pool.max-active}")
    private int maxActive;


    @Bean
    public RedisConnectionFactory lettuceConnectionFactory() {
        RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration(master, nodes);
        NamedNode master = redisSentinelConfiguration.getMaster();
        String name = master.getName();
        //redisSentinelConfiguration.setPassword(RedisPassword.of(password.toCharArray()));
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxIdle(maxIdle);
        genericObjectPoolConfig.setMinIdle(minIdle);
        genericObjectPoolConfig.setMaxTotal(maxActive);
        genericObjectPoolConfig.setMaxWaitMillis(maxWait);
        //readFrom(ReadFrom.REPLICA) 可设置,设置了就形成读写分离,读会读取从节点,但是因为有复制过程,要能容忍短时间的脏数据,适合对数据要求不太及时的
        LettucePoolingClientConfiguration lettuceClientConfiguration = LettucePoolingClientConfiguration.builder()
                .poolConfig(genericObjectPoolConfig).readFrom(ReadFrom.REPLICA)
                .build();


        return new LettuceConnectionFactory(redisSentinelConfiguration, lettuceClientConfiguration);
    }


    public void setNodes(Set<String> nodes) {
        this.nodes = nodes;
    }

    public void setMaster(String master) {
        this.master = master;
    }

}
RedisService
@Service
public class RedisSentinelService {

    @Autowired
    @Resource(name = "stringRedisTemplate")
    private RedisTemplate redisTemplate;

    public void redisM1(){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("s1","测试redis联通");
    }
}
RediSentinelController
@RestController
@RequestMapping("/rediSentinel")
public class RediSentinelController {

    @Autowired
    private RedisSentinelService redisSentinelService;

    @GetMapping("redisSentinelM1")
    public void redisSentinelM1() {
        redisSentinelService.redisM1();
    }
}

 

posted @ 2022-01-16 16:02  爵士灬  阅读(2988)  评论(0编辑  收藏  举报