您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

redis_conn.py 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import json
  2. import valkey as redis
  3. import logging
  4. from rag import settings
  5. from rag.utils import singleton
  6. class Payload:
  7. def __init__(self, consumer, queue_name, group_name, msg_id, message):
  8. self.__consumer = consumer
  9. self.__queue_name = queue_name
  10. self.__group_name = group_name
  11. self.__msg_id = msg_id
  12. self.__message = json.loads(message['message'])
  13. def ack(self):
  14. try:
  15. self.__consumer.xack(self.__queue_name, self.__group_name, self.__msg_id)
  16. return True
  17. except Exception as e:
  18. logging.warning("[EXCEPTION]ack" + str(self.__queue_name) + "||" + str(e))
  19. return False
  20. def get_message(self):
  21. return self.__message
  22. @singleton
  23. class RedisDB:
  24. def __init__(self):
  25. self.REDIS = None
  26. self.config = settings.REDIS
  27. self.__open__()
  28. def __open__(self):
  29. try:
  30. self.REDIS = redis.StrictRedis(host=self.config["host"].split(":")[0],
  31. port=int(self.config.get("host", ":6379").split(":")[1]),
  32. db=int(self.config.get("db", 1)),
  33. password=self.config.get("password"),
  34. decode_responses=True)
  35. except Exception:
  36. logging.warning("Redis can't be connected.")
  37. return self.REDIS
  38. def health(self):
  39. self.REDIS.ping()
  40. a, b = 'xx', 'yy'
  41. self.REDIS.set(a, b, 3)
  42. if self.REDIS.get(a) == b:
  43. return True
  44. def is_alive(self):
  45. return self.REDIS is not None
  46. def exist(self, k):
  47. if not self.REDIS: return
  48. try:
  49. return self.REDIS.exists(k)
  50. except Exception as e:
  51. logging.warning("[EXCEPTION]exist" + str(k) + "||" + str(e))
  52. self.__open__()
  53. def get(self, k):
  54. if not self.REDIS: return
  55. try:
  56. return self.REDIS.get(k)
  57. except Exception as e:
  58. logging.warning("[EXCEPTION]get" + str(k) + "||" + str(e))
  59. self.__open__()
  60. def set_obj(self, k, obj, exp=3600):
  61. try:
  62. self.REDIS.set(k, json.dumps(obj, ensure_ascii=False), exp)
  63. return True
  64. except Exception as e:
  65. logging.warning("[EXCEPTION]set_obj" + str(k) + "||" + str(e))
  66. self.__open__()
  67. return False
  68. def set(self, k, v, exp=3600):
  69. try:
  70. self.REDIS.set(k, v, exp)
  71. return True
  72. except Exception as e:
  73. logging.warning("[EXCEPTION]set" + str(k) + "||" + str(e))
  74. self.__open__()
  75. return False
  76. def transaction(self, key, value, exp=3600):
  77. try:
  78. pipeline = self.REDIS.pipeline(transaction=True)
  79. pipeline.set(key, value, exp, nx=True)
  80. pipeline.execute()
  81. return True
  82. except Exception as e:
  83. logging.warning("[EXCEPTION]set" + str(key) + "||" + str(e))
  84. self.__open__()
  85. return False
  86. def queue_product(self, queue, message, exp=settings.SVR_QUEUE_RETENTION) -> bool:
  87. for _ in range(3):
  88. try:
  89. payload = {"message": json.dumps(message)}
  90. pipeline = self.REDIS.pipeline()
  91. pipeline.xadd(queue, payload)
  92. #pipeline.expire(queue, exp)
  93. pipeline.execute()
  94. return True
  95. except Exception:
  96. logging.exception("producer" + str(queue) + " got exception")
  97. return False
  98. def queue_consumer(self, queue_name, group_name, consumer_name, msg_id=b">") -> Payload:
  99. try:
  100. group_info = self.REDIS.xinfo_groups(queue_name)
  101. if not any(e["name"] == group_name for e in group_info):
  102. self.REDIS.xgroup_create(
  103. queue_name,
  104. group_name,
  105. id="0",
  106. mkstream=True
  107. )
  108. args = {
  109. "groupname": group_name,
  110. "consumername": consumer_name,
  111. "count": 1,
  112. "block": 10000,
  113. "streams": {queue_name: msg_id},
  114. }
  115. messages = self.REDIS.xreadgroup(**args)
  116. if not messages:
  117. return None
  118. stream, element_list = messages[0]
  119. msg_id, payload = element_list[0]
  120. res = Payload(self.REDIS, queue_name, group_name, msg_id, payload)
  121. return res
  122. except Exception as e:
  123. if 'key' in str(e):
  124. pass
  125. else:
  126. logging.exception("consumer: " + str(queue_name) + " got exception")
  127. return None
  128. def get_unacked_for(self, consumer_name, queue_name, group_name):
  129. try:
  130. group_info = self.REDIS.xinfo_groups(queue_name)
  131. if not any(e["name"] == group_name for e in group_info):
  132. return
  133. pendings = self.REDIS.xpending_range(queue_name, group_name, min=0, max=10000000000000, count=1, consumername=consumer_name)
  134. if not pendings: return
  135. msg_id = pendings[0]["message_id"]
  136. msg = self.REDIS.xrange(queue_name, min=msg_id, count=1)
  137. _, payload = msg[0]
  138. return Payload(self.REDIS, queue_name, group_name, msg_id, payload)
  139. except Exception as e:
  140. if 'key' in str(e):
  141. return
  142. logging.exception("xpending_range: " + consumer_name + " got exception")
  143. self.__open__()
  144. REDIS_CONN = RedisDB()