與MySQL主從複製,從節點能夠分擔部分讀壓力不同,甚至能夠增長slave或者slave的slave來分擔讀壓力,Redis集羣中的從節點,默認是不分擔讀請求的,從節點只做爲主節點的備份,僅負責故障轉移。
若是是主節點讀寫壓力過大,能夠經過增長集羣節點數量的方式來分擔壓力。html
如下簡單測試Redis集羣讀寫時候的節點相應狀況,節點集羣關係以下,三個主節點組成集羣,分別對應三個從節點node
往集羣中寫入10W條「字符串類型」的測試數據python
#!/usr/bin/env python3 import time from time import ctime,sleep from rediscluster import StrictRedisCluster startup_nodes = [ {"host":"127.0.0.1", "port":9000}, {"host":"127.0.0.1", "port":9001}, {"host":"127.0.0.1", "port":9002}, {"host":"127.0.0.1", "port":9003}, {"host":"127.0.0.1", "port":9004}, {"host":"127.0.0.1", "port":9005} ] redis_conn= StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True) for i in range(0, 100000): try: redis_conn.set('name'+str(i),str(i) except: print("connect to redis cluster error") #time.sleep(2)
10W個key值基本上均勻地落在三個節點上redis
連續讀數據測試,同時觀察某一個主從節點的負載c#
#!/usr/bin/env python3 import time from time import ctime,sleep from rediscluster import StrictRedisCluster startup_nodes = [ {"host":"127.0.0.1", "port":9000}, {"host":"127.0.0.1", "port":9001}, {"host":"127.0.0.1", "port":9002}, {"host":"127.0.0.1", "port":9003}, {"host":"127.0.0.1", "port":9004}, {"host":"127.0.0.1", "port":9005} ] redis_conn= StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True) for i in range(0, 100000): try: redis_conn.get('name'+str(i)) except: print("connect to redis cluster error") time.sleep(2)
這裏以9000和9003集羣中的一對主從節點爲例,當查詢發起時,同時觀察這兩個節點的負載,
能夠發現主節點9000負責處理定位到當前節點的請求,與此同時,而對應的從節點9003則沒有處理請求信息。服務器
Redis集羣中,默認狀況下,查詢是根據key值的slot信息找到其對應的主節點,而後進行查詢,而不會在從節點上發起查詢測試
使用readonly命令打開客戶端鏈接只讀狀態,則從節點能夠接受讀請求(固然在slave節點上讀,由於複製延遲形成的問題另說)this
根據https://redis-py-cluster.readthedocs.io/en/master/readonly-mode.html中的說明,
You can overcome this limitation [for scaling read with READONLY mode](http://redis.io/topics/cluster-spec#scaling-reads-using-slave-nodes).
redis-py-cluster also implements this mode. You can access slave by passing readonly_mode=True to StrictRedisCluster (or RedisCluster) constructor.spa
經過以readonly_mode=True的方式鏈接至集羣,重複一下測試,發現從節點依然沒有處理讀請求3d
#!/usr/bin/env python3 import time from time import ctime,sleep from rediscluster import StrictRedisCluster startup_nodes = [ {"host":"127.0.0.1", "port":9000}, {"host":"127.0.0.1", "port":9001}, {"host":"127.0.0.1", "port":9002}, {"host":"127.0.0.1", "port":9003}, {"host":"127.0.0.1", "port":9004}, {"host":"127.0.0.1", "port":9005} ] redis_conn= StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True, readonly_mode=True) for i in range(0, 100000): try: print(redis_conn.get('name'+str(i))) except: print("connect to redis cluster error") time.sleep(2000)
Redis版本爲 5.0.4
不知道爲何slave節點沒有請求讀處理,觀察Redis請求處理的stat狀態,依舊重定向到了master節點,不知道是否與單機多實例有關
若是每一個實例獨立部署在一臺機器上,readonly_mode=True的訪問模式,slave節點就能夠處理讀請求?
ps:測試環境是在騰訊雲服務器EC2上安裝的Redis,若是要在本地訪問,須要bind的IP爲內網的IP,而後本地用公網IP訪問,而不是直接bind公網IP,爲此折騰了一陣子。