Redis学习之三 —— 基于Redis Sentinel的Redis集群(主从&分片)高可用客户端方案

以你之姓@ 2022-03-02 02:22 409阅读 0赞

Redis集群(主从、分片)概念

之前讲过一主多从的哨兵(Sentinel)模式,只有一个主,称为单实例的Redis,现在讲的是多主多从方案。

现在公司用到的就是 多个一主一从组成的Redis集群,通过 Sentinel监控多个主从,多个主就称为Redis数据分片,数据被分不到多个实例上,每个实例都是主从结构,以下是Java客户端怎么用这种集群方案。

Sentinel出现的问题

Sentinel&Jedis看上去是个完美的解决方案,这句话只说对了一半,在无分片的情况是这样,但我们的应用使用了数据分片-sharing,数据被平均分布到4个不同的实例上,每个实例以主从结构部署,Jedis没有提供基于Sentinel的ShardedJedisPool,也就是说在4个分片中,如果其中一个分片发生主从切换,应用所使用的ShardedJedisPool无法获得通知,所有对那个分片的操作将会失败。
本文提供一个基于Sentinel的ShardedJedisPool,能及时感知所有分片主从切换行为,进行连接池重建,源码见https://github.com/warmbreeze/sharded-jedis-sentinel-pool/blob/master/src/main/java/redis/clients/jedis/ShardedJedisSentinelPool.java

ShardedJedisSentinelPool实现分析

类似之前的Jedis Pool的构造方法,需要参数poolConfig提供诸如maxIdle,maxTotal之类的配置,masters是一个List,用来保存所有分片Master在Sentinel中配置的名字(注意master的顺序不能改变,因为Shard算法是依据分片位置进行计算,如果顺序错误将导致数据存储混乱),sentinels是一个Set,其中存放所有Sentinel的地址(格式:IP:PORT,如127.0.0.1:26379),顺序无关;

  1. public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
  2. final GenericObjectPoolConfig poolConfig, int timeout,
  3. final String password, final int database) {
  4. this.poolConfig = poolConfig;
  5. this.timeout = timeout;
  6. this.password = password;
  7. this.database = database;
  8. List<HostAndPort> masterList = initSentinels(sentinels, masters);
  9. initPool(masterList);
  10. }

从sentinel集群获取所有分片的master地址

循环所有分片,循环所有sentinel,获取master地址,给initPool

  1. private List<HostAndPort> initSentinels(Set<String> sentinels, final List<String> masters) {
  2. Map<String, HostAndPort> masterMap = new HashMap<String, HostAndPort>();
  3. List<HostAndPort> shardMasters = new ArrayList<HostAndPort>();
  4. log.info("Trying to find all master from available Sentinels...");
  5. for (String masterName : masters) {
  6. HostAndPort master = null;
  7. boolean fetched = false;
  8. while (!fetched && sentinelRetry < MAX_RETRY_SENTINEL) {
  9. for (String sentinel : sentinels) {
  10. final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel.split(":")));
  11. log.info("Connecting to Sentinel " + hap);
  12. try {
  13. Jedis jedis = new Jedis(hap.getHost(), hap.getPort());
  14. master = masterMap.get(masterName);
  15. if (master == null) {
  16. List<String> hostAndPort = jedis.sentinelGetMasterAddrByName(masterName);
  17. if (hostAndPort != null && hostAndPort.size() > 0) {
  18. master = toHostAndPort(hostAndPort);
  19. log.info("Found Redis master at " + master);
  20. shardMasters.add(master);
  21. masterMap.put(masterName, master);
  22. fetched = true;
  23. jedis.disconnect();
  24. break;
  25. }
  26. }
  27. } catch (JedisConnectionException e) {
  28. log.warn("Cannot connect to sentinel running @ " + hap + ". Trying next one.");
  29. }
  30. }
  31. if (null == master) {
  32. try {
  33. log.warn("All sentinels down, cannot determine where is "
  34. + masterName + " master is running... sleeping 1000ms, Will try again.");
  35. Thread.sleep(1000);
  36. } catch (InterruptedException e) {
  37. e.printStackTrace();
  38. }
  39. fetched = false;
  40. sentinelRetry++;
  41. }
  42. }
  43. // Try MAX_RETRY_SENTINEL times.
  44. if (!fetched && sentinelRetry >= MAX_RETRY_SENTINEL) {
  45. log.warn("All sentinels down and try " + MAX_RETRY_SENTINEL + " times, Abort.");
  46. throw new JedisConnectionException("Cannot connect all sentinels, Abort.");
  47. }
  48. }
  49. // All shards master must been accessed.
  50. if (masters.size() != 0 && masters.size() == shardMasters.size()) {
  51. log.info("Starting Sentinel listeners...");
  52. for (String sentinel : sentinels) {
  53. final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel.split(":")));
  54. MasterListener masterListener = new MasterListener(masters, hap.getHost(), hap.getPort());
  55. masterListeners.add(masterListener);
  56. masterListener.start();
  57. }
  58. }
  59. return shardMasters;
  60. }
  61. private void initPool(List<HostAndPort> masters) {
  62. if (!equals(currentHostMasters, masters)) {
  63. StringBuffer sb = new StringBuffer();
  64. for (HostAndPort master : masters) {
  65. sb.append(master.toString());
  66. sb.append(" ");
  67. }
  68. log.info("Created ShardedJedisPool to master at [" + sb.toString() + "]");
  69. List<JedisShardInfo> shardMasters = makeShardInfoList(masters);
  70. // 这个initPool是redis.clients.util.Pool的方法
  71. initPool(poolConfig, new ShardedJedisFactory(shardMasters, Hashing.MURMUR_HASH, null));
  72. currentHostMasters = masters;
  73. }
  74. }

这样就完成了连接池初始化了。

监控每个Sentinel,当出现主从切换时,重新初始化连接池

在方法
e6f32bb5-f983-3ffe-97f2-a7fa7ce9d26f.png
最后,会为每个Sentinel启动一个Thread来监控Sentinel做出的更改:
1507c655-a4e7-33c5-bb22-38edb76fb1d5.png
该线程的run方法通过Jedis Pub/Sub API(实现JedisPubSub接口,并通过jedis.subscribe进行订阅)向Sentinel实例订阅“+switch-master”频道,当Sentinel进行主从切换时,该线程会得到新Master地址的通知,通过master name判断哪个分片进行了切换,将新master地址替换原来位置的地址,并调用initPool(List masters)进行Jedis连接池重建;后续所有通过该连接池取得的连接都指向新Master地址,对应用程序透明;

全部代码:

  1. package com.artisan.redis.pool;
  2. import org.apache.commons.pool2.PooledObject;
  3. import org.apache.commons.pool2.PooledObjectFactory;
  4. import org.apache.commons.pool2.impl.DefaultPooledObject;
  5. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
  6. import org.apache.log4j.Logger;
  7. import redis.clients.jedis.*;
  8. import redis.clients.jedis.exceptions.JedisConnectionException;
  9. import redis.clients.util.Hashing;
  10. import redis.clients.util.Pool;
  11. import java.util.*;
  12. import java.util.concurrent.atomic.AtomicBoolean;
  13. import java.util.regex.Pattern;
  14. /**
  15. * Created by 18121254 on 2019/3/19.
  16. */
  17. public class ShardedJedisSentinelPool extends Pool<ShardedJedis> {
  18. public static final int MAX_RETRY_SENTINEL = 10;
  19. protected final Logger log = Logger.getLogger(getClass().getName());
  20. protected GenericObjectPoolConfig poolConfig;
  21. protected int timeout = Protocol.DEFAULT_TIMEOUT;
  22. private int sentinelRetry = 0;
  23. protected String password;
  24. protected int database = Protocol.DEFAULT_DATABASE;
  25. protected Set<MasterListener> masterListeners = new HashSet<MasterListener>();
  26. private volatile List<HostAndPort> currentHostMasters;
  27. public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels) {
  28. this(masters, sentinels, new GenericObjectPoolConfig(),
  29. Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);
  30. }
  31. public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels, String password) {
  32. this(masters, sentinels, new GenericObjectPoolConfig(),
  33. Protocol.DEFAULT_TIMEOUT, password);
  34. }
  35. public ShardedJedisSentinelPool(final GenericObjectPoolConfig poolConfig, List<String> masters, Set<String> sentinels) {
  36. this(masters, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
  37. Protocol.DEFAULT_DATABASE);
  38. }
  39. public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
  40. final GenericObjectPoolConfig poolConfig, int timeout,
  41. final String password) {
  42. this(masters, sentinels, poolConfig, timeout, password,
  43. Protocol.DEFAULT_DATABASE);
  44. }
  45. public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
  46. final GenericObjectPoolConfig poolConfig, final int timeout) {
  47. this(masters, sentinels, poolConfig, timeout, null,
  48. Protocol.DEFAULT_DATABASE);
  49. }
  50. public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
  51. final GenericObjectPoolConfig poolConfig, final String password) {
  52. this(masters, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT,
  53. password);
  54. }
  55. public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
  56. final GenericObjectPoolConfig poolConfig, int timeout,
  57. final String password, final int database) {
  58. this.poolConfig = poolConfig;
  59. this.timeout = timeout;
  60. this.password = password;
  61. this.database = database;
  62. List<HostAndPort> masterList = initSentinels(sentinels, masters);
  63. initPool(masterList);
  64. }
  65. public void destroy() {
  66. for (MasterListener m : masterListeners) {
  67. m.shutdown();
  68. }
  69. super.destroy();
  70. }
  71. public List<HostAndPort> getCurrentHostMaster() {
  72. return currentHostMasters;
  73. }
  74. private void initPool(List<HostAndPort> masters) {
  75. if (!equals(currentHostMasters, masters)) {
  76. StringBuffer sb = new StringBuffer();
  77. for (HostAndPort master : masters) {
  78. sb.append(master.toString());
  79. sb.append(" ");
  80. }
  81. log.info("Created ShardedJedisPool to master at [" + sb.toString() + "]");
  82. List<JedisShardInfo> shardMasters = makeShardInfoList(masters);
  83. initPool(poolConfig, new ShardedJedisFactory(shardMasters, Hashing.MURMUR_HASH, null));
  84. currentHostMasters = masters;
  85. }
  86. }
  87. private boolean equals(List<HostAndPort> currentShardMasters, List<HostAndPort> shardMasters) {
  88. if (currentShardMasters != null && shardMasters != null) {
  89. if (currentShardMasters.size() == shardMasters.size()) {
  90. for (int i = 0; i < currentShardMasters.size(); i++) {
  91. if (!currentShardMasters.get(i).equals(shardMasters.get(i))) return false;
  92. }
  93. return true;
  94. }
  95. }
  96. return false;
  97. }
  98. private List<JedisShardInfo> makeShardInfoList(List<HostAndPort> masters) {
  99. List<JedisShardInfo> shardMasters = new ArrayList<JedisShardInfo>();
  100. for (HostAndPort master : masters) {
  101. JedisShardInfo jedisShardInfo = new JedisShardInfo(master.getHost(), master.getPort(), timeout);
  102. jedisShardInfo.setPassword(password);
  103. shardMasters.add(jedisShardInfo);
  104. }
  105. return shardMasters;
  106. }
  107. private List<HostAndPort> initSentinels(Set<String> sentinels, final List<String> masters) {
  108. Map<String, HostAndPort> masterMap = new HashMap<String, HostAndPort>();
  109. List<HostAndPort> shardMasters = new ArrayList<HostAndPort>();
  110. log.info("Trying to find all master from available Sentinels...");
  111. for (String masterName : masters) {
  112. HostAndPort master = null;
  113. boolean fetched = false;
  114. while (!fetched && sentinelRetry < MAX_RETRY_SENTINEL) {
  115. for (String sentinel : sentinels) {
  116. final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel.split(":")));
  117. log.info("Connecting to Sentinel " + hap);
  118. try {
  119. Jedis jedis = new Jedis(hap.getHost(), hap.getPort());
  120. master = masterMap.get(masterName);
  121. if (master == null) {
  122. List<String> hostAndPort = jedis.sentinelGetMasterAddrByName(masterName);
  123. if (hostAndPort != null && hostAndPort.size() > 0) {
  124. master = toHostAndPort(hostAndPort);
  125. log.info("Found Redis master at " + master);
  126. shardMasters.add(master);
  127. masterMap.put(masterName, master);
  128. fetched = true;
  129. jedis.disconnect();
  130. break;
  131. }
  132. }
  133. } catch (JedisConnectionException e) {
  134. log.warn("Cannot connect to sentinel running @ " + hap + ". Trying next one.");
  135. }
  136. }
  137. if (null == master) {
  138. try {
  139. log.warn("All sentinels down, cannot determine where is "
  140. + masterName + " master is running... sleeping 1000ms, Will try again.");
  141. Thread.sleep(1000);
  142. } catch (InterruptedException e) {
  143. e.printStackTrace();
  144. }
  145. fetched = false;
  146. sentinelRetry++;
  147. }
  148. }
  149. // Try MAX_RETRY_SENTINEL times.
  150. if (!fetched && sentinelRetry >= MAX_RETRY_SENTINEL) {
  151. log.warn("All sentinels down and try " + MAX_RETRY_SENTINEL + " times, Abort.");
  152. throw new JedisConnectionException("Cannot connect all sentinels, Abort.");
  153. }
  154. }
  155. // All shards master must been accessed.
  156. if (masters.size() != 0 && masters.size() == shardMasters.size()) {
  157. log.info("Starting Sentinel listeners...");
  158. for (String sentinel : sentinels) {
  159. final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel.split(":")));
  160. MasterListener masterListener = new MasterListener(masters, hap.getHost(), hap.getPort());
  161. masterListeners.add(masterListener);
  162. masterListener.start();
  163. }
  164. }
  165. return shardMasters;
  166. }
  167. private HostAndPort toHostAndPort(List<String> getMasterAddrByNameResult) {
  168. String host = getMasterAddrByNameResult.get(0);
  169. int port = Integer.parseInt(getMasterAddrByNameResult.get(1));
  170. return new HostAndPort(host, port);
  171. }
  172. /**
  173. * PoolableObjectFactory custom impl.
  174. */
  175. protected static class ShardedJedisFactory implements PooledObjectFactory<ShardedJedis> {
  176. private List<JedisShardInfo> shards;
  177. private Hashing algo;
  178. private Pattern keyTagPattern;
  179. public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
  180. this.shards = shards;
  181. this.algo = algo;
  182. this.keyTagPattern = keyTagPattern;
  183. }
  184. public PooledObject<ShardedJedis> makeObject() throws Exception {
  185. ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
  186. return new DefaultPooledObject<ShardedJedis>(jedis);
  187. }
  188. public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis) throws Exception {
  189. final ShardedJedis shardedJedis = pooledShardedJedis.getObject();
  190. for (Jedis jedis : shardedJedis.getAllShards()) {
  191. try {
  192. try {
  193. jedis.quit();
  194. } catch (Exception e) {
  195. }
  196. jedis.disconnect();
  197. } catch (Exception e) {
  198. }
  199. }
  200. }
  201. public boolean validateObject(PooledObject<ShardedJedis> pooledShardedJedis) {
  202. try {
  203. ShardedJedis jedis = pooledShardedJedis.getObject();
  204. for (Jedis shard : jedis.getAllShards()) {
  205. if (!shard.ping().equals("PONG")) {
  206. return false;
  207. }
  208. }
  209. return true;
  210. } catch (Exception ex) {
  211. return false;
  212. }
  213. }
  214. public void activateObject(PooledObject<ShardedJedis> p) throws Exception {
  215. }
  216. public void passivateObject(PooledObject<ShardedJedis> p) throws Exception {
  217. }
  218. }
  219. protected class JedisPubSubAdapter extends JedisPubSub {
  220. @Override
  221. public void onMessage(String channel, String message) {
  222. }
  223. @Override
  224. public void onPMessage(String pattern, String channel, String message) {
  225. }
  226. @Override
  227. public void onPSubscribe(String pattern, int subscribedChannels) {
  228. }
  229. @Override
  230. public void onPUnsubscribe(String pattern, int subscribedChannels) {
  231. }
  232. @Override
  233. public void onSubscribe(String channel, int subscribedChannels) {
  234. }
  235. @Override
  236. public void onUnsubscribe(String channel, int subscribedChannels) {
  237. }
  238. }
  239. protected class MasterListener extends Thread {
  240. protected List<String> masters;
  241. protected String host;
  242. protected int port;
  243. protected long subscribeRetryWaitTimeMillis = 5000;
  244. protected Jedis jedis;
  245. protected AtomicBoolean running = new AtomicBoolean(false);
  246. protected MasterListener() {
  247. }
  248. public MasterListener(List<String> masters, String host, int port) {
  249. this.masters = masters;
  250. this.host = host;
  251. this.port = port;
  252. }
  253. public MasterListener(List<String> masters, String host, int port,
  254. long subscribeRetryWaitTimeMillis) {
  255. this(masters, host, port);
  256. this.subscribeRetryWaitTimeMillis = subscribeRetryWaitTimeMillis;
  257. }
  258. public void run() {
  259. running.set(true);
  260. while (running.get()) {
  261. jedis = new Jedis(host, port);
  262. try {
  263. jedis.subscribe(new JedisPubSubAdapter() {
  264. @Override
  265. public void onMessage(String channel, String message) {
  266. log.info("Sentinel " + host + ":" + port + " published: " + message + ".");
  267. String[] switchMasterMsg = message.split(" ");
  268. if (switchMasterMsg.length > 3) {
  269. int index = masters.indexOf(switchMasterMsg[0]);
  270. if (index >= 0) {
  271. HostAndPort newHostMaster = toHostAndPort(Arrays.asList(switchMasterMsg[3], switchMasterMsg[4]));
  272. List<HostAndPort> newHostMasters = new ArrayList<HostAndPort>();
  273. for (int i = 0; i < masters.size(); i++) {
  274. newHostMasters.add(null);
  275. }
  276. Collections.copy(newHostMasters, currentHostMasters);
  277. newHostMasters.set(index, newHostMaster);
  278. initPool(newHostMasters);
  279. } else {
  280. StringBuffer sb = new StringBuffer();
  281. for (String masterName : masters) {
  282. sb.append(masterName);
  283. sb.append(",");
  284. }
  285. log.info("Ignoring message on +switch-master for master name "
  286. + switchMasterMsg[0]
  287. + ", our monitor master name are ["
  288. + sb + "]");
  289. }
  290. } else {
  291. log.warn("Invalid message received on Sentinel "
  292. + host
  293. + ":"
  294. + port
  295. + " on channel +switch-master: "
  296. + message);
  297. }
  298. }
  299. }, "+switch-master");
  300. } catch (JedisConnectionException e) {
  301. if (running.get()) {
  302. log.warn("Lost connection to Sentinel at " + host
  303. + ":" + port
  304. + ". Sleeping 5000ms and retrying.");
  305. try {
  306. Thread.sleep(subscribeRetryWaitTimeMillis);
  307. } catch (InterruptedException e1) {
  308. e1.printStackTrace();
  309. }
  310. } else {
  311. log.info("Unsubscribing from Sentinel at " + host + ":"
  312. + port);
  313. }
  314. }
  315. }
  316. }
  317. public void shutdown() {
  318. try {
  319. log.info("Shutting down listener on " + host + ":" + port);
  320. running.set(false);
  321. // This isn't good, the Jedis object is not thread safe
  322. jedis.disconnect();
  323. } catch (Exception e) {
  324. log.warn("Caught exception while shutting down: " + e.getMessage());
  325. }
  326. }
  327. }
  328. }

发表评论

表情:
评论列表 (有 0 条评论,409人围观)

还没有评论,来说两句吧...

相关阅读