千家信息网

【Redis】获取没有设置ttl的key脚本

发表于:2024-09-21 作者:千家信息网编辑
千家信息网最后更新 2024年09月21日,一 前言在运维Redis的时候,总会遇到使用不规范的业务设计,比如没有对key设置ttl,进而导致内存空间吃紧,通常的解决方法是在slave上dump 出来所有的key ,然后对文件进行遍历再分析。遇
千家信息网最后更新 2024年09月21日【Redis】获取没有设置ttl的key脚本

一 前言

在运维Redis的时候,总会遇到使用不规范的业务设计,比如没有对key设置ttl,进而导致内存空间吃紧,通常的解决方法是在slave上dump 出来所有的key ,然后对文件进行遍历再分析。遇到几十G的Redis实例,dump + 分析 会是一个比较耗时的操作,为此,我开发了一个小脚本直接连接Redis 进行scan 遍历所有的key,然后在检查key的ttl,将没有ttl的key输出到指定的文件里面。

二 代码实现

  1. # encoding: utf-8
  2. """
  3. author: yangyi@youzan.com
  4. time: 2018/4/26 下午4:34
  5. func: 获取数据库中没有设置ttl的 key
  6. """
  7. import redis
  8. import argparse
  9. import time
  10. import sys


  11. class ShowProcess:
  12. """
  13. 显示处理进度的类
  14. 调用该类相关函数即可实现处理进度的显示
  15. """
  16. i = 0 # 当前的处理进度
  17. max_steps = 0 # 总共需要处理的次数
  18. max_arrow = 50 # 进度条的长度

  19. # 初始化函数,需要知道总共的处理次数
  20. def __init__(self, max_steps):
  21. self.max_steps = max_steps
  22. self.i = 0

  23. # 显示函数,根据当前的处理进度i显示进度
  24. # 效果为[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]100.00%
  25. def show_process(self, i = None):
  26. if i is not None:
  27. self.i = i
  28. else:
  29. self.i += 1
  30. num_arrow = int(self.i * self.max_arrow / self.max_steps) # 计算显示多少个'>'
  31. num_line = self.max_arrow - num_arrow # 计算显示多少个'-'
  32. percent = self.i * 100.0 / self.max_steps # 计算完成进度,格式为xx.xx%
  33. process_bar = '[' + '>' * num_arrow + ' ' * num_line + ']'\
  34. + '%.2f' % percent + '%' + '\r' # 带输出的字符串,'\r'表示不换行回到最左边
  35. sys.stdout.write(process_bar) # 这两句打印字符到终端
  36. sys.stdout.flush()

  37. def close(self, words='done'):
  38. print ''
  39. print words
  40. self.i = 0


  41. def check_ttl(redis_conn, no_ttl_file, dbindex):
  42. start_time = time.time()
  43. no_ttl_num = 0
  44. keys_num = redis_conn.dbsize()
  45. print "there are {num} keys in db {index} ".format(num=keys_num, index=dbindex)
  46. process_bar = ShowProcess(keys_num)
  47. with open(no_ttl_file, 'a') as f:

  48. for key in redis_conn.scan_iter(count=1000):
  49. process_bar.show_process()
  50. if redis_conn.ttl(key) == -1:
  51. no_ttl_num += 1
  52. if no_ttl_num < 1000:
  53. f.write(key+'\n')
  54. else:
  55. continue

  56. process_bar.close()
  57. print "cost time(s):", time.time() - start_time
  58. print "no ttl keys number:", no_ttl_num
  59. print "we write keys with no ttl to the file: %s" % no_ttl_file


  60. def main():
  61. parser = argparse.ArgumentParser()
  62. parser.add_argument('-p', type=int, dest='port', action='store', help='port of redis ')
  63. parser.add_argument('-d', type=str, dest='db_list', action='store', default=0,
  64. help='ex : -d all / -d 1,2,3,4 ')
  65. args = parser.parse_args()
  66. port = args.port
  67. if args.db_list == 'all':
  68. db_list = [i for i in xrange(0, 16)]
  69. else:
  70. db_list = [int(i) for i in args.db_list.split(',')]

  71. for index in db_list:
  72. try:
  73. pool = redis.ConnectionPool(host='127.0.0.1', port=port, db=index)
  74. r = redis.StrictRedis(connection_pool=pool)
  75. except redis.exceptions.ConnectionError as e:
  76. print e
  77. else:
  78. no_ttl_keys_file = "/tmp/{port}_{db}_no_ttl_keys.txt".format(port=port, db=index)
  79. check_ttl(r, no_ttl_keys_file, index)


  80. if __name__ == '__main__':
  81. main()




注意:
代码里面对没有ttl的key的输出做了限制,大家使用的时候可以调整阈值 或者去掉 全部输出到指定的文件里面。欢迎大家使用,并给出功能或者算法上的改进措施。




0