redis配置master-slave模式

由于云服务器存在闪断现象,项目线上会存在基于redis的功能在闪断时段内出现异常,所以redis需要做master-slave模式。直接上代码:

原单机redis,RedisConnectionFactory设置代码

```
@Bean
public RedisConnectionFactory jedisConnectionFactory(){
JedisPoolConfig poolConfig=new JedisPoolConfig();
poolConfig.setMaxIdle(5);
poolConfig.setMinIdle(1);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setNumTestsPerEvictionRun(10);
poolConfig.setTimeBetweenEvictionRunsMillis(60000);

JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
//单机redis的host、port设置
jedisConnectionFactory.setHostName(redishost);
jedisConnectionFactory.setPort(redisport);
jedisConnectionFactory.setDatabase(0);


return jedisConnectionFactory;
}
```
哨兵节点设置代码

```
@Bean
public RedisConnectionFactory jedisConnectionFactory(){
JedisPoolConfig poolConfig=new JedisPoolConfig();
poolConfig.setMaxIdle(5);
poolConfig.setMinIdle(1);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setNumTestsPerEvictionRun(10);
poolConfig.setTimeBetweenEvictionRunsMillis(60000);
//哨兵节点host、port设置,可设置多个哨兵,只需要链式新增 .sentinel(sentinelhost, sentinelport)
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration() .master("mymaster")
.sentinel(sentinelhost, sentinelport);
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfig,poolConfig);

return jedisConnectionFactory;
}
```

由此,在master节点down了的时候,slave节点会自动升级到master。然后我们的服务会自动新建redis连接池到新的master节点。

```
2016-07-29 10:42:28,525 [MasterListener-mymaster-[10.10.180.37:26379]] INFO redis.clients.jedis.JedisSentinelPool - Created JedisPool to master at 10.10.129.188:6379
```

当哨兵节点down了的时候,服务日志会提示Lost connection to Sentinel,此时redis连接池不会断开,可继续使用,不影响业务,但是这时当master失去响应时就不会自动切换连接池了。为了避免这种情况可以配置多个哨兵(sentinel)节点,也可以通过sentinel配置文件的方式,当哨兵节点down了之后,通知运维同学。

```
2016-07-29 10:50:36,820 [MasterListener-mymaster-[10.10.180.37:26379]] ERROR redis.clients.jedis.JedisSentinelPool - Lost connection to Sentinel at 10.10.180.37:26379. Sleeping 5000ms and retrying.
2016-07-29 10:50:41,821 [MasterListener-mymaster-[10.10.180.37:26379]] ERROR redis.clients.jedis.JedisSentinelPool - Lost connection to Sentinel at 10.10.180.37:26379. Sleeping 5000ms and retrying.
2016-07-29 10:50:46,823 [MasterListener-mymaster-[10.10.180.37:26379]] ERROR redis.clients.jedis.JedisSentinelPool - Lost connection to Sentinel at 10.10.180.37:26379. Sleeping 5000ms and retrying.
2016-07-29 10:50:51,825 [MasterListener-mymaster-[10.10.180.37:26379]] ERROR redis.clients.jedis.JedisSentinelPool - Lost connection to Sentinel at 10.10.180.37:26379. Sleeping 5000ms and retrying.
2016-07-29 10:50:56,826 [MasterListener-mymaster-[10.10.180.37:26379]] ERROR redis.clients.jedis.JedisSentinelPool - Lost connection to Sentinel at 10.10.180.37:26379. Sleeping 5000ms and retrying.

posted @ 2017-05-03 17:35  托马斯布莱克  阅读(1403)  评论(0编辑  收藏  举报