Springboot2.x集成Redis哨兵模式

oZaoHua 2019-12-17

Springboot2.x集成Redis哨兵模式

说明

Redis哨兵模式是Redis高可用方案的一种实现方式,通过哨兵来自动实现故障转移,从而保证高可用。

准备条件

pom.xml中引入相关jar

<!-- 集成Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    
        <!-- Jedis 客户端 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
    
        <!-- lettuce客户端需要使用到 -->
          <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
           </dependency>

application.yml哨兵模式配置属性示例。

spring:
  redis:
    host: 192.168.8.121
    port: 6379
    password: enjoyitlife
    timeout: 30000
    jedis:
      pool:
        max-active: 256
        max-wait: 30000
        max-idle: 64
        min-idle: 32
    lettuce:
      pool:
        max-active: 256
        max-idle: 64
        max-wait: 30000
        min-idle: 32
    sentinel:
      master: mymaster
      nodes: 192.168.8.121:26379, 192.168.8.121:26380,192.168.8.121:26381

哨兵模式下的整合教程

Jedis客户端整合

JedisSentinleConfig.java 相关配置

package top.enjoyitlife.redis.jedis;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

@Configuration
@Profile("JedisSentinel")
public class JedisSentinleConfig {

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;
    
    @Value("${spring.redis.password}")
    private String password;
    
    @Value("${spring.redis.sentinel.master}")
    private String sentinelName;
    
    @Value("${spring.redis.sentinel.nodes}")
    private String[] sentinels;
    
     @Bean
     public JedisSentinelPool redisPoolFactory()  throws Exception{
            JedisPoolConfig  jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxIdle(maxIdle);
            jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
            Set<String> sentinelsets = new HashSet<String>(Arrays.asList(sentinels));
            JedisSentinelPool  pool = new JedisSentinelPool(sentinelName,sentinelsets,jedisPoolConfig,password);
            return pool;
     }
    
     @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
            RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new StringRedisSerializer());
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }        
}

Lettuce客户端整合

package top.enjoyitlife.redis.lettuce;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
@Profile("lettuceSentinel")
public class LettuceSentinelConfig {
    
    @Value("${spring.redis.sentinel.master}")
    private String sentinelName;
    
    @Value("${spring.redis.password}")
    private String password;
    
    @Value("${spring.redis.sentinel.nodes}")
    private String[] sentinels;
    
    
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisSentinelConfiguration rsc= new RedisSentinelConfiguration();
        rsc.setMaster(sentinelName);
        List<RedisNode> redisNodeList= new ArrayList<RedisNode>();
        for (String sentinel : sentinels) {
                String[] nodes = sentinel.split(":");
                redisNodeList.add(new RedisNode(nodes[0], Integer.parseInt(nodes[1])));
        }
        rsc.setSentinels(redisNodeList);
        rsc.setPassword(password);
        return new LettuceConnectionFactory(rsc);
    }
    

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

Springboot通过RedisSentinelConfiguration来统一了连接哨兵的方式,区别Jedis客户端是通过JedisConnectionFactory进行初始化,而Lettuce客户端是通过LettuceConnectionFactory初始化。

单元测试

Jedis单元测试

package top.enjoyitlife.redis.jedis;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@ActiveProfiles("JedisSentinel")
class JedisSentinelTest {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Test
    void contextLoads() {
        String name=redisTemplate.opsForValue().get("name").toString();
        System.out.println(name);
    }

}

Lettuce 单元测试

package top.enjoyitlife.redis.lettuce;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.lettuce.LettucePool;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ActiveProfiles;

import redis.clients.jedis.JedisPool;

@SpringBootTest
@ActiveProfiles("lettuceSentinel")
class LettuceSentinelTest {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    
    @Test
    void contextLoads() {
        String name = redisTemplate.opsForValue().get("name").toString();
        System.out.println(name);
    }

}

好了以上就是Springboot2.x集成Redis哨兵模式的代码示例,希望对你能有所帮助。谢谢阅读。

相关推荐

DiamondTao / 0评论 2020-08-30