【Redis】 redis-cluster刪除指定的key

小亮520cl發表於2018-05-07

需要從redis-cluster中刪除指定的key


迴圈每個主節點的版本:

  1. [root@ip-172-31-39-42 ~]# more delkey-single.py
  2. # encoding: utf-8

  3. import redis
  4. import random
  5. import string
  6. import rediscluster
  7. import time
  8. 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']


  9. def del_keys_without_pipe(newhost):
  10.     pool = redis.ConnectionPool(host=newhost, port=6379, db=0,password='inH7HkD7iXoxKZCi')
  11.     r = redis.StrictRedis(connection_pool=pool)
  12.     start_time = time.time()
  13.     result_length = 0
  14.     for key in r.scan_iter(match='user:*:type:*:news:msg', count=100):
  15.         if r.ttl(key) == -1:     如果未設定過期時間
  16.            print key
  17.    # r.delete(key)
  18.         result_length += 1
  19.     print "normal ways end at:", time.time() - start_time
  20.     print newhost,"normal ways delete numbers:", result_length
  21. for i in all_nodes:
  22.         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





連結叢集版本

  1. [root@ip-172-31-39-42 ~]# more delkey-cluster.py
  2. # encoding: utf-8

  3. import redis
  4. import random
  5. import string
  6. import rediscluster
  7. import time


  8. def del_keys_without_pipe():
  9.     startup_nodes = [{"host": "172.31.39.42", "port": 6379,"db":0}]
  10.     r = rediscluster.StrictRedisCluster(startup_nodes=startup_nodes, password='inH7HkD7iXoxKZCi')
  11.     start_time = time.time()
  12.     result_length = 0
  13.     for key in r.scan_iter(match='user:*:type:*:news:msg', count=100):
  14.     # r.delete(key)
  15.         result_length += 1
  16.     print "normal ways end at:", time.time() - start_time
  17.     print "normal ways delete numbers:", result_length

  18. del_keys_without_pipe()

綜合以上兩種方式,還是使用連結cluster的方式吧,使用的模組也不一樣!

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29096438/viewspace-2153950/,如需轉載,請註明出處,否則將追究法律責任。

相關文章