实现原理:
1、客户端遍历Sentinel节点集合,获取一个可用的Sentinel节点(可以ping通的节点)
2、调用sentinel的api,获取master节点信息
sentinel get-master-addr-by-name masterName
3、客户端获取到master信息后,执行role命令,验证其是否为真正的master
4、sentinel感知到master发生了变化后,会发布订阅到指定频道,客户端之前已经订阅了该频道,就能感知到master的变化
使用方法
private static void testSentinel(){
String masterName = "mymaster";
Set<String> sentinels = new HashSet<String>();
sentinels.add("sentinel的ip和port");
sentinels.add("sentinel的ip和port");
sentinels.add("sentinel的ip和port");
JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(masterName,sentinels);
while (true){
Jedis jedis = null;
try {
jedis = jedisSentinelPool.getResource();
int index = new Random().nextInt(10000);
String key = "key-" + index;
String value = "value-" + index;
jedis.set(key, value);
System.out.println("key:" + key + ",value:" + jedis.get(key));
Thread.sleep(10);
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
if(jedis != null){
jedis.close();
}
}
}
网友评论