Jedis源碼分析共有四個章節,如下爲各章連接:java
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
下文爲構建Jedis分片的方法(單節點與對象池的模式),code
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);
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個重要變量:
圖2-2爲 ShardedJedis
的初始化流程,經過傳入待分片的節點信息,初始化好上述3個變量。在使用時,先根據key計算出hash值,在nodes
中找到對應的分片信息,再在resources
中找到對應的Jedis實例,而後經過這個Jedis實例才操做redis節點。