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节点。