You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 satır
4.0KB

  1. import redis
  2. import os
  3. from config import conf
  4. import uuid
  5. import time
  6. import threading
  7. # 定义全局 redis_helper
  8. redis_helper = None
  9. class RedisHelper:
  10. def __init__(self, host='localhost', port=6379, password=None ,db=0):
  11. # 初始化 Redis 连接
  12. self.client = redis.Redis(host=host, port=port,db=db,password=password)
  13. def set_hash(self, hash_key, data, timeout=None):
  14. """添加或更新哈希,并设置有效期"""
  15. self.client.hset(hash_key, mapping=data)
  16. if timeout:
  17. # 设置有效期(单位:秒)
  18. self.client.expire(hash_key, timeout)
  19. def get_hash(self, hash_key):
  20. """获取整个哈希表数据"""
  21. result = self.client.hgetall(hash_key)
  22. # 将字节数据解码成字符串格式返回
  23. return {k.decode('utf-8'): v.decode('utf-8') for k, v in result.items()}
  24. def get_hash_field(self, hash_key, field):
  25. """获取哈希表中的单个字段值"""
  26. result = self.client.hget(hash_key, field)
  27. return result.decode('utf-8') if result else None
  28. def delete_hash(self, hash_key):
  29. """删除整个哈希表"""
  30. self.client.delete(hash_key)
  31. def delete_hash_field(self, hash_key, field):
  32. """删除哈希表中的某个字段"""
  33. self.client.hdel(hash_key, field)
  34. def update_hash_field(self, hash_key, field, value):
  35. """更新哈希表中的某个字段"""
  36. self.client.hset(hash_key, field, value)
  37. # def acquire_lock(self, lock_name, timeout=60):
  38. # """
  39. # 尝试获取分布式锁,成功返回 True,失败返回 False
  40. # :param lock_name: 锁的名称
  41. # :param timeout: 锁的超时时间(秒)
  42. # :return: bool
  43. # """
  44. # identifier = str(time.time()) # 使用时间戳作为唯一标识
  45. # end_time = time.time() + timeout
  46. # while time.time() < end_time:
  47. # if self.client.set(lock_name, identifier, nx=True, ex=timeout):
  48. # self.lock_renewal_thread = threading.Thread(target=self.renew_lock, args=(lock_name, identifier, timeout))
  49. # self.lock_renewal_thread.start()
  50. # return True
  51. # time.sleep(0.1)
  52. # return False
  53. def acquire_lock(self, lock_name, timeout=60):
  54. """
  55. 尝试获取分布式锁,成功返回 True,失败返回 False
  56. :param lock_name: 锁的名称
  57. :param timeout: 锁的超时时间(秒)
  58. :return: bool
  59. """
  60. identifier = str(time.time()) # 使用时间戳作为唯一标识
  61. if self.client.set(lock_name, identifier, nx=True, ex=timeout):
  62. self.lock_renewal_thread = threading.Thread(target=self.renew_lock, args=(lock_name, identifier, timeout))
  63. self.lock_renewal_thread.start()
  64. return True
  65. return False
  66. def renew_lock(self, lock_name, identifier, timeout):
  67. """
  68. 锁的自动续期
  69. :param lock_name: 锁的名称
  70. :param identifier: 锁的唯一标识
  71. :param timeout: 锁的超时时间(秒)
  72. """
  73. while True:
  74. time.sleep(timeout / 2)
  75. if self.client.get(lock_name) == identifier.encode():
  76. self.client.expire(lock_name, timeout)
  77. else:
  78. break
  79. def release_lock(self, lock_name, identifier):
  80. """
  81. 释放分布式锁
  82. :param lock_name: 锁的名称
  83. :param identifier: 锁的唯一标识
  84. """
  85. if self.client.get(lock_name) == identifier.encode():
  86. self.client.delete(lock_name)
  87. if self.lock_renewal_thread:
  88. self.lock_renewal_thread.join()
  89. def start():
  90. global redis_helper
  91. host=conf().get("redis_host")
  92. port=conf().get("redis_port")
  93. password=conf().get("redis_password")
  94. db=conf().get("redis_db")
  95. redis_helper = RedisHelper(host=host,port=port,password=password,db=db)