redis 哨兵(sentinel)

时间:2022-03-22 16:20:59

redis哨兵

  • 哨兵自动故障转移
  • 自动通知应用最新master信息
  • 无需担心,master挂了,程序不需要修改IP啥的,由哨兵自动完成
  1. 修改sentinel.conf
protected-mode no # 默认只允许本机访问sentinel服务

工具类

package redis.client.sentinel;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool; import java.util.HashSet;
import java.util.Map;
import java.util.Set; /**
* Created by dailin on 2017/7/27.
*/
public class Redis_Sentinel { public static JedisSentinelPool sentinelPool = null;
private static JedisPoolConfig jedisPoolConfig = null; private Redis_Sentinel(){} private static void initSentinelPool(Set<String> sentinels){
synchronized (Redis_Sentinel.class){
if (sentinelPool == null) {
GenericObjectPoolConfig gPoolConfig=new GenericObjectPoolConfig();
gPoolConfig.setMaxIdle(10);
gPoolConfig.setMaxTotal(10);
gPoolConfig.setMinIdle(1);
gPoolConfig.setMaxWaitMillis(10);
gPoolConfig.setJmxEnabled(true);
sentinelPool = new JedisSentinelPool("mymaster",sentinels,gPoolConfig);
}
}
} public static Jedis getJedis(Set<String> sentinels){
initSentinelPool(sentinels);
return sentinelPool.getResource();
}
public static void returnJedis(Jedis jedis){
sentinelPool.returnResource(jedis);
}
}

  

测试类

import org.junit.Before;
import org.junit.Test;
import redis.client.sentinel.Redis_Sentinel;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis; import java.util.HashSet;
import java.util.List;
import java.util.Set; /**
* Created by dailin on 2017/7/27.
*/
public class TestSentinel {
Set<String> sentinel = null;
@Before
public void init()
{
sentinel = new HashSet<String>();
sentinel.add("192.168.56.130:26379");
sentinel.add("192.168.56.131:26379");
}
@Test
public void testSentinel(){
while(true) {
try{
Jedis jedis = Redis_Sentinel.getJedis(sentinel);
String result = jedis.get("dai");
HostAndPort currentHostMaster = Redis_Sentinel.sentinelPool.getCurrentHostMaster();
System.out.println("master:"+currentHostMaster.getHost()+"-port:"+currentHostMaster.getPort());
Redis_Sentinel.returnJedis(jedis);
System.out.println(result);
}catch (Exception e){
e.printStackTrace();
}
} }
}

  

这个测试类会一直访问redis,当master被停止后,程序抛出异常,过了一小会新的master被选出,程序又正常执行,所以使用jedis连接redis时,只需要传入sentinel的地址即可,自动在redis的master宕机后,自动更新连接新master信息。