用redis-py从Redis集群中获取全部数据
这篇文章使用Python库redis-py从Redis Cluster中获取所有数据的标题。
政策
-
- 全マスターノードでSCAN
全スロットでCLUSTER COUNTKEYSINSLOTでKEY数を取得しCLUSTER GETKEYSINSLOTでKEYを取得
我认为有两种策略。
这次将采取后一种方式。
环境
-
- Python 3.7.10
-
- redis-py 4.3.4
- hiredis 2.0.0
$ python --version
Python 3.7.10
$ pip list | grep redis
hiredis 2.0.0
redis 4.3.4
尝试获取全部
连接到Redis集群
from redis.cluster import RedisCluster, ClusterNode
nodes = [
{"host": "host_name_1", "port": 6379},
{"host": "host_name_2", "port": 6379},
{"host": "host_name_3", "port": 6379}
]
cluster_nodes = [ClusterNode(**node) for node in nodes]
redis_cluster = RedisCluster(startup_nodes=cluster_nodes, readonly_mode=True)
获取所有的槽位键。
slot_id = 0
num_keys = redis_cluster.cluster_countkeysinslot(slot_id)
keys = redis_cluster.cluster_get_keys_in_slot(slot_id, num_keys)
通过这个方法,可以获取特定槽位slot_id的关键词数。
如果槽位使用默认设置,可以通过使用for循环等方法获取所有数据(0至16383槽位范围内)。
以下是在对话模式下尝试后的结果。
>>> slot_id = 1392
>>> num_keys = redis_cluster.cluster_countkeysinslot(slot_id)
>>> num_keys
1
>>> keys = redis_cluster.cluster_get_keys_in_slot(slot_id, num_keys)
>>> keys
['key_name']
>>>
请注意
当使用SCAN系列命令获取时,与使用CLUSTER GETKEYSINSLOT命令相比,返回的键的类型是不同的。(失败次数1)
使用SCAN系列命令时,返回的键是以字节(bytes)形式表示的,而使用CLUSTER GETKEYSINSLOT命令返回的键则是以字符串(str)形式表示的。
>>> type(redis_cluster.cluster_get_keys_in_slot(slot_id, num_keys)[0])
<class 'str'>
>>>
>>> type(next(redis_cluster.scan_iter(match='*')))
<class 'bytes'>
>>>
请给出以下代码的中文翻译,只需一个选项:
总结一下我所做的事情,大概是这个感觉。
from redis.cluster import RedisCluster, ClusterNode
nodes = [
{"host": "host_name_1", "port": 6379},
{"host": "host_name_2", "port": 6379},
{"host": "host_name_3", "port": 6379}
]
cluster_nodes = [ClusterNode(**node) for node in nodes]
redis_cluster = RedisCluster(startup_nodes=cluster_nodes, readonly_mode=True)
for slot_id in range(16384):
num_keys = redis_cluster.cluster_countkeysinslot(slot_id)
keys = redis_cluster.cluster_get_keys_in_slot(slot_id, num_keys)
# keysを使った何かの処理