Jedis源碼分析(四)-JedisSentinel與ShardedJedis介紹

Jedis源碼分析共有四個章節,如下爲各章連接:java

  1. Jedis源碼分析(一)-Jedis介紹
  2. Jedis源碼分析(二)-Jedis類結構及實現
  3. Jedis源碼分析(三)- JedisCluster類結構及實現
  4. Jedis源碼分析(四)-JedisSentinel與ShardedJedis介紹

1 JedisSentinel

JedisSentinel經常使用方式有兩種:node

1.使用哨兵單節點拿到主節點,從節點的信息redis

//經過哨兵節點的信息新建Jedis實例,而後拿到Master節點的信息
Jedis j = new Jedis(sentinel);
List<Map<String, String>> masters = j.sentinelMasters();
//拿到master的address,**MASTER_NAME**
List<String> masterHostAndPort = j.sentinelGetMasterAddrByName(**MASTER_NAME**);
HostAndPort masterFromSentinel = new HostAndPort(masterHostAndPort.get(0),Integer.parseInt(masterHostAndPort.get(1)));
assertEquals(master, masterFromSentinel);
//經過哨兵節點,拿到從節點的信息
List<Map<String, String>> slaves = j.sentinelSlaves(**MASTER_NAME**);

2.使用哨兵節點對象池segmentfault

Set<String> sentinels = new HashSet<String>();
sentinels.add(new HostAndPort("localhost", 65432).toString());
sentinels.add(new HostAndPort("localhost", 65431).toString());
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels);
pool.destroy();

JedisSentinelPool的結構清晰,內部使用對象池存放一個個sentinel實例。圖2-12和2-13分別爲JedisSentinelPool的類結構和初始化流程。在使用時,咱們先根據,host,port等信息,初始化一個Jedis實例,而後能夠經過sentinelMasters()sentinelGetMasterAddrByName(MASTER_NAME)sentinelSlaves(MASTER_NAME)等方法拿到這個哨兵節點監聽的MASTER節點信息或對應的SLAVE節點信息。函數

圖片描述

​ 圖1.1 JedisSentinelPool 的類結構源碼分析

圖片描述

​ 圖1.2 JedisSentinelPool 的初始化流程spa

2 ShardedJedis

下文爲構建Jedis分片的方法(單節點與對象池的模式),code

  1. 單節點模式
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(2);
//其中一個分片
JedisShardInfo shard1 = new JedisShardInfo(redis1);
shards.add(shard1);
//另外一個分片
JedisShardInfo shard2 = new JedisShardInfo(redis2);
shards.add(shard2);
@SuppressWarnings("resource")
//新建ShardedJedis實例
ShardedJedis shardedJedis = new ShardedJedis(shards);
shardedJedis.set("a", "bar");
//經過key能夠查看存儲在哪一個jedis
JedisShardInfo ak = shardedJedis.getShardInfo("a");
assertEquals(shard2, ak);
  1. 對象池模式
ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));

圖片描述
圖2-1 ShardedJedis的類結構對象

圖片描述

​ 圖2-2 ShardedJedis的初始化流程blog

​ 圖2-1爲ShardedJedis的類結構(其內部保存一個對象池,與常規的JedisPool的不一樣之處在於,內部的PooledObjectFactory實現不一樣),分片信息保存在基類Sharded中,Sharded保存了3個重要變量:

  1. nodes是一個TreeMap,保存了每一個分片節點和對應的hash值。
  2. algo是計算hash值的函數,默認是MurmurHash,可替換。
  3. resources是一個LinkedHashMap,存放着JedisShardinfo和一個Jedis實例的對應關係。

​ 圖2-2爲 ShardedJedis的初始化流程,經過傳入待分片的節點信息,初始化好上述3個變量。在使用時,先根據key計算出hash值,在nodes中找到對應的分片信息,再在resources中找到對應的Jedis實例,而後經過這個Jedis實例才操做redis節點。

相關文章
相關標籤/搜索