天天看點

7.3 Redis哨兵之用戶端連接配接

1.用戶端實作基本原理

(1).step1

擷取所有Sentinel節點和masterName,周遊Sentinel集合得到一個可用(即可以ping通)的Sentinel節點。

7.3 Redis哨兵之用戶端連接配接

(2).step2

向可用的Sentinel節點發送Sentinel的get-master-addr-by-name的請求(參數masterName)來擷取master節點資訊。

7.3 Redis哨兵之用戶端連接配接

(3).step3

用戶端擷取master節點後,會執行一次role或者role replication來驗證其是否是master節點。

7.3 Redis哨兵之用戶端連接配接

(4).master節點發生變化,Sentinel是感覺的(所有的故障發現、轉移是由sentinel做的)。那麼Sentinel怎麼通知client的呢?内部是一個釋出訂閱的模式,client訂閱Sentinel的某一個頻道,該頻道裡有誰是master的資訊,假如變化的Sentinel就在頻道裡publish一條消息,client就可以擷取到資訊,通過新的master資訊進行連接配接。

7.3 Redis哨兵之用戶端連接配接

(5).用戶端實作基本原理

7.3 Redis哨兵之用戶端連接配接

2.用戶端介入

(1).流程

  • Sentinel位址集合
  • masterName
  • 不是代理模式
public class JedisSentinelDemo {
    public static void main(String[] args) {
        //設定連接配接池資訊
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(50);
        jedisPoolConfig.setMaxWaitMillis(1000);
        //設定Sentinel所有節點資訊
        Set<String> sentinelSet = new HashSet<>();
        sentinelSet.add("47.***.***.140:26379");//172.17.31.46
        sentinelSet.add("39.***.***.47:26379");
        sentinelSet.add("39.***.***.3:26379");//172.24.6.215
        JedisSentinelPool sentinelPool = new JedisSentinelPool("mymaster", sentinelSet, jedisPoolConfig, 10 * 1000);
        int counter = 0;
        while (true) {
            counter++;
            Jedis jedis = null;
            try {
                jedis = sentinelPool.getResource();
                //将key的值設定為10000以内的數
                Random random = new Random();
                int index = random.nextInt(10000) + 1;
                String key = "k-" + index;
                String value = "v-" + index;
                jedis.set(key, value);
                if (counter % 100 == 0) {
                    System.out.println("key:" + key + ",value" + jedis.get(key));
                }
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (jedis != null) {
                    jedis.close();
                }
            }
        }
    }
}      
19:04:57.824 [main] INFO redis.clients.jedis.JedisSentinelPool - Trying to find master from available Sentinels...
19:04:57.827 [main] DEBUG redis.clients.jedis.JedisSentinelPool - Connecting to Sentinel 47.***.***.140:26379
19:04:57.892 [main] DEBUG redis.clients.jedis.JedisSentinelPool - Found Redis master at 47.***.***.140:6379
19:04:57.892 [main] INFO redis.clients.jedis.JedisSentinelPool - Redis master running at 47.***.***.140:6379, starting Sentinel listeners...
19:04:57.996 [main] INFO redis.clients.jedis.JedisSentinelPool - Created JedisPool to master at 47.***.***.140:6379      
key:k-7504,valuev-7504
key:k-6910,valuev-6910
......      

繼續閱讀