需要从redis-cluster中删除指定的key
循环每个主节点的版本:
- [root@ip-172-31-39-42 ~]# more delkey-single.py
- # encoding: utf-8
-
- import redis
- import random
- import string
- import rediscluster
- import time
- all_nodes=['172.31.39.42','172.31.36.10','172.31.47.157','172.31.36.49','172.31.40.169','172.31.32.234']
-
-
- def del_keys_without_pipe(newhost):
- pool = redis.ConnectionPool(host=newhost, port=6379, db=0,password='inH7HkD7iXoxKZCi')
- r = redis.StrictRedis(connection_pool=pool)
- start_time = time.time()
- result_length = 0
- for key in r.scan_iter(match='user:*:type:*:news:msg', count=100):
- if r.ttl(key) == -1: 如果未设置过期时间
- print key
- # r.delete(key)
- result_length += 1
- print "normal ways end at:", time.time() - start_time
- print newhost,"normal ways delete numbers:", result_length
- for i in all_nodes:
- del_keys_without_pipe(i)
注意:循环链接只能去链接主节点,如果链接从节点会报以下的错误:
>>> for key in r.scan_iter(count=10):
... if r.ttl(key) == -1:
... print key
...
Traceback (most recent call last):
File "", line 2, in
File "/usr/lib/python2.7/site-packages/redis/client.py", line 1231, in ttl
return self.execute_command('TTL', name)
File "/usr/lib/python2.7/site-packages/redis/client.py", line 668, in execute_command
return self.parse_response(connection, command_name, **options)
File "/usr/lib/python2.7/site-packages/redis/client.py", line 680, in parse_response
response = connection.read_response()
File "/usr/lib/python2.7/site-packages/redis/connection.py", line 629, in read_response
raise response
redis.exceptions.ResponseError: MOVED 12752 172.31.32.234:6379
链接集群版本
- [root@ip-172-31-39-42 ~]# more delkey-cluster.py
- # encoding: utf-8
-
- import redis
- import random
- import string
- import rediscluster
- import time
-
-
- def del_keys_without_pipe():
- startup_nodes = [{"host": "172.31.39.42", "port": 6379,"db":0}]
- r = rediscluster.StrictRedisCluster(startup_nodes=startup_nodes, password='inH7HkD7iXoxKZCi')
- start_time = time.time()
- result_length = 0
- for key in r.scan_iter(match='user:*:type:*:news:msg', count=100):
- # r.delete(key)
- result_length += 1
- print "normal ways end at:", time.time() - start_time
- print "normal ways delete numbers:", result_length
-
- del_keys_without_pipe()
综合以上两种方式,还是使用链接cluster的方式吧,使用的模块也不一样!
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29096438/viewspace-2153950/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29096438/viewspace-2153950/