sentinel 高可用
- sentinel 的高可用是服务端的高可用;
- 服务端的 master 挂了可以完成故障转移,客户端如果感知不到这个转移是没有作用的;
客户端高可用基本原理
- client 拿着 sentinel 节点集合 + materName,遍历 sentinel 集合,获取一个可用的 sentinel 节点;
- client 拿着 masterName 向获取到的可用的 sentinel 节点要 master 的地址;
- client 拿着 master 的地址验证一下其到底是不是 master;
- 如果 master 发生的转移,sentinel 是可以感知的,client 和 sentinel 之间的通知是通过发布订阅模式,client 订阅了 sentinel 的某个频道,频道中有 master 的变化,如果 master 发生了变化,就会在这个频道中发布一条消息,订阅的 client 就可以获取,在取新的 master 进行连接;
客户端接入流程
- sentinel 地址集合;
- materName;
- 不是代理模式,只有第一次连接的时候通过 sentinel,后面直接连 master 了;
JedisSentinelPool 示例
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import java.util.HashSet;
import java.util.Set;
public class JedisSentinel {
public static void main(String[] args) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(10);
config.setMaxWaitMillis(1000);
String masterName = "mymaster";
Set<String> sentinelSet = new HashSet<>();
sentinelSet.add("127.0.0.1:26379");
sentinelSet.add("127.0.0.1:26380");
sentinelSet.add("127.0.0.1:26381");
JedisSentinelPool pool = new JedisSentinelPool(masterName, sentinelSet, config);
Jedis jedis = null;
try {
jedis = pool.getResource();
String value = jedis.get("hello");
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}