广告
返回顶部
首页 > 资讯 > 数据库 >【Redis】获取没有设置ttl的key脚本
  • 891
分享到

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

2024-04-02 19:04:59 891人浏览 薄情痞子
摘要

一 前言       在运维Redis的时候,总会遇到使用不规范的业务设计,比如没有对key设置ttl,进而导致内存空间吃紧,通常的解决方法是在slave上du

一 前言 

     在运维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()
您可能感兴趣的文档:

--结束END--

本文标题: 【Redis】获取没有设置ttl的key脚本

本文链接: https://www.lsjlt.com/news/49928.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作