Redis集群(九):Redis Sharding集群Redis節點主從切換后客戶端自動重新連接


上文介紹了Redis Sharding集群的使用, 點擊閱讀
本文介紹當某個Redis節點的Master節點發生問題,發生主從切換時,Jedis怎樣自動重連新的Master節點

​一、步驟如下:
1、配置三組主從結構的redis集群, 參考

2、設置哨兵(某個master節點):哨兵的作用主要是監控master節點的狀態,當master節點掛掉時通過選舉機制選出一個slave節點成為一個新的master,哨兵的使用可 參考
   sentinel.conf配置說明,下面的mymaster很重要,表示是master節點的名稱,jedis指定master使用該名稱,而不是IP+端口
   sentinel monitor mymaster 127.0.0.1 6379 1

3、使用ShardedJedisSentinelPool連接池
   a) 該類是一個開源項目,地址為: https://github.com/warmbreeze/sharded-jedis-sentinel-pool
   b)  ShardedJedisSentinelPool通過MasterListener線程(有幾個哨兵就有幾個線程) 監控哨兵的狀態,如果對應的master節點發生問題,如主從切換,則通過redis的pub/sub該監聽器線程
   c) MasterListener的run方法調用initPool重置連接池,即連接新的master機器
   d) 調用pool.getResource() 發生主從切換,當次redis操作使用新的master機器
   e) 調用 pool.getResource()發生主從切換,當次redis操作無效並拋出SocketException,下次redis恢復正常

二、示例代碼:由於機器有限,只配置了一台機器,多台原理一樣
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class ShardedSentinelTest {
 
     public static void main(String[] args) {
         GenericObjectPoolConfig config = new GenericObjectPoolConfig();
 
         List<String> masters = new ArrayList<String>();
         masters.add( "mymaster" );
 
 
         Set<String> sentinels = new HashSet<String>();
         sentinels.add( "xxxxxx:29111" );
 
 
         ShardedJedisSentinelPool pool = new ShardedJedisSentinelPool(masters, sentinels, config, 60000 );
         ShardedJedis jedis = pool.getResource();
 
         for ( int i = 1 ; i < 10000 ; i++) {
             String val = jedis.set( "ss" + i, "vv" + i);
             System.out.println(jedis.get( "ss" + i));
         }
         jedis.close();
         pool.destroy();
     }
}

三、參考文檔
  1. http://www.tuicool.com/articles/naeEJbv  基於Redis Sentinel的Redis集群(主從&Sharding)高可用方案
  2. http://blog.csdn.net/dc_726/article/details/48084373 Jedis分片Sentinel連接池實驗


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM