springboot 集成Redis一主二从三哨兵

1、Centos7 Redis一主二从三哨兵配置

 Redis一主二从三哨兵环境搭建

2、接入过程

与集成redis单机不同的是jedis相关的配置做了修改,JedisPool换成了JedisSentinelPool,相关改动如下:

  application文件:

# Redis
spring.redis:
    sentinel:
    #与Redis环境配置的保持一致 master: mymaster #从节点集合 nodes: localhost:26388,localhost:26380,localhost:26381 password: root timeout: 1000 jedis.pool: #jedis最大分配对象 maxTotal: 1024 #jedis最大保存idel状态对象数 maxIdle: 200 #jedis池没有对象返回时,最大等待时间 maxWaitMillis: 10000 testOnBorrow: true testOnReturn: true blockWhenExhausted: false #Idle时进行连接扫描 testWhileIdle: true #表示idle object evitor两次扫描之间要sleep的毫秒数 timeBetweenEvictionRunsMillis: 30000 #表示idle object evitor每次扫描的最多的对象数 numTestsPerEvictionRun: 10 #表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义 minEvictableIdleTimeMillis: 60000

  jedis配置类:

@Configuration
@Data
public class RedisConfig {

    private Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Bean(name = "jedis.pool")
    @Autowired
    public JedisSentinelPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config,
                                       @Value("${spring.redis.sentinel.master}") String clusterName,
                                       @Value("${spring.redis.sentinel.nodes}") String sentinelNodes,
                                       @Value("${spring.redis.timeout}") int timeout,
                                       @Value("${spring.redis.password}") String password) {
        logger.info("缓存服务器的主服务名称:" + clusterName + ", 主从服务ip&port:" + sentinelNodes);
        Assert.isTrue(StringUtils.isNotEmpty(clusterName), "主服务名称配置为空");
        Assert.isTrue(StringUtils.isNotEmpty(sentinelNodes), "主从服务地址配置为空");

        Set<String> sentinels = Sets.newHashSet(StringUtils.split(sentinelNodes, ","));

        JedisSentinelPool sentinelJedisPool = new JedisSentinelPool(clusterName, sentinels, config, Protocol.DEFAULT_TIMEOUT, password);

        return sentinelJedisPool;
    }

    @Bean(name = "jedis.pool.config")
    public JedisPoolConfig jedisPoolConfig(@Value("${spring.redis.jedis.pool.maxTotal}") int maxTotal,
                                           @Value("${spring.redis.jedis.pool.maxIdle}") int maxIdle,
                                           @Value("${spring.redis.jedis.pool.maxWaitMillis}") int maxWaitMillis,
                                           @Value("${spring.redis.jedis.pool.testOnBorrow}") boolean testOnBorrow,
                                           @Value("${spring.redis.jedis.pool.testOnReturn}") boolean testOnReturn,
                                           @Value("${spring.redis.jedis.pool.blockWhenExhausted}") boolean blockWhenExhausted,
                                           @Value("${spring.redis.jedis.pool.testWhileIdle}") boolean testWhileIdle,
                                           @Value("${spring.redis.jedis.pool.timeBetweenEvictionRunsMillis}") long timeBetweenEvictionRunsMillis,
                                           @Value("${spring.redis.jedis.pool.numTestsPerEvictionRun}") int numTestsPerEvictionRun,
                                           @Value("${spring.redis.jedis.pool.minEvictableIdleTimeMillis}") long minEvictableIdleTimeMillis) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setBlockWhenExhausted(blockWhenExhausted);
        config.setTestWhileIdle(testWhileIdle);
        config.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        config.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

        return config;
    }

}

  RedisClient类:

@Component
public class RedisClient {

    private static final Logger logger = LoggerFactory.getLogger(RedisClient.class);

    @Autowired
    private JedisSentinelPool jedisPool;

    public Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return Boolean
     */
    public String set(final String key, String value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.set(key, String.valueOf(value));
        } catch (Exception e) {
            logger.error("[RedisClient] set e,", e);
            return "";
        } finally {
            close(jedis);
        }
    }

  /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Optional<String> get(final String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return Optional.ofNullable(jedis.get(key));
        } catch (Exception e) {
            logger.error("[RedisClient] get exception,", e);
            return Optional.empty();
        } finally {
            close(jedis);
        }
    }
}

 

源码参照:Github

 

posted @ 2019-02-20 16:48  花拾夕  阅读(4548)  评论(0编辑  收藏  举报