renew_redis.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import datetime
  2. import redis
  3. def extend_redis_key_expiry(host='localhost', port=6379, db=0, password=None, threshold_second=60, extend_second=300):
  4. """
  5. 扫描 Redis key,如果过期时间小于 threshold_days 天,则过期时间延长 extend_days 天。
  6. Args:
  7. host: Redis 主机地址。
  8. port: Redis 端口。
  9. db: Redis 数据库编号。
  10. password: Redis 密码(如果没有则为 None)。
  11. threshold_second: 过期时间阈值(秒)。
  12. extend_second: 延长时间(秒)。
  13. """
  14. try:
  15. print(f'time = {datetime.datetime.now()}')
  16. r = redis.Redis(host=host, port=port, db=db, password=password)
  17. count = 0
  18. renew_count = 0
  19. # 获取所有 key (生产环境谨慎使用 keys '*')
  20. # 建议使用 scan_iter 迭代 key,避免阻塞 Redis
  21. for key in r.scan_iter(match='mid:generate:timestamp*', count=1000):
  22. # for key in r.scan_iter(match='renew_1*', count=1000):
  23. ttl = r.ttl(key)
  24. print(f'key: {key}, ttl: {ttl}')
  25. if ttl is not None and ttl > 0: # 检查 key 是否设置了过期时间
  26. if ttl < threshold_second:
  27. r.expire(key, ttl + extend_second) # 在原过期时间基础上延长
  28. print(f"Key: {key.decode()}, 原 TTL: {ttl} 秒, 延长 {extend_second} 秒")
  29. renew_count += 1
  30. count += 1
  31. if count % 1000000 == 0:
  32. print(f"count: {count}")
  33. print(f"扫描完成 count: {count} renew_count: {renew_count} time = {datetime.datetime.now()}")
  34. except redis.exceptions.ConnectionError as e:
  35. print(f"连接 Redis 失败: {e}")
  36. except Exception as e:
  37. print(f"发生错误: {e}")
  38. if __name__ == "__main__":
  39. # 或者指定 Redis 连接参数
  40. threshold_second = 7 * 24 * 60 * 60
  41. extend_second = 20 * 24 * 60 * 60
  42. # test
  43. # extend_redis_key_expiry(host='r-bp1ps6my7lzg8rdhwx682.redis.rds.aliyuncs.com', port=6379, db=0, password='Wqsd@2019', threshold_second=threshold_second, extend_second=extend_second)
  44. # prod
  45. extend_redis_key_expiry(host='r-bp1j1vsznx8h813ddk.redis.rds.aliyuncs.com', port=6379, db=0, password='Wqsd@2019', threshold_second=threshold_second, extend_second=extend_second)