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.

redis_conn.py 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import logging
  2. import json
  3. import valkey as redis
  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(
  31. host=self.config["host"].split(":")[0],
  32. port=int(self.config.get("host", ":6379").split(":")[1]),
  33. db=int(self.config.get("db", 1)),
  34. password=self.config.get("password"),
  35. decode_responses=True,
  36. )
  37. except Exception:
  38. logging.warning("Redis can't be connected.")
  39. return self.REDIS
  40. def health(self):
  41. self.REDIS.ping()
  42. a, b = "xx", "yy"
  43. self.REDIS.set(a, b, 3)
  44. if self.REDIS.get(a) == b:
  45. return True
  46. def is_alive(self):
  47. return self.REDIS is not None
  48. def exist(self, k):
  49. if not self.REDIS:
  50. return
  51. try:
  52. return self.REDIS.exists(k)
  53. except Exception as e:
  54. logging.warning("RedisDB.exist " + str(k) + " got exception: " + str(e))
  55. self.__open__()
  56. def get(self, k):
  57. if not self.REDIS:
  58. return
  59. try:
  60. return self.REDIS.get(k)
  61. except Exception as e:
  62. logging.warning("RedisDB.get " + str(k) + " got exception: " + str(e))
  63. self.__open__()
  64. def set_obj(self, k, obj, exp=3600):
  65. try:
  66. self.REDIS.set(k, json.dumps(obj, ensure_ascii=False), exp)
  67. return True
  68. except Exception as e:
  69. logging.warning("RedisDB.set_obj " + str(k) + " got exception: " + str(e))
  70. self.__open__()
  71. return False
  72. def set(self, k, v, exp=3600):
  73. try:
  74. self.REDIS.set(k, v, exp)
  75. return True
  76. except Exception as e:
  77. logging.warning("RedisDB.set " + str(k) + " got exception: " + str(e))
  78. self.__open__()
  79. return False
  80. def sadd(self, key: str, member: str):
  81. try:
  82. self.REDIS.sadd(key, member)
  83. return True
  84. except Exception as e:
  85. logging.warning("RedisDB.sadd " + str(key) + " got exception: " + str(e))
  86. self.__open__()
  87. return False
  88. def srem(self, key: str, member: str):
  89. try:
  90. self.REDIS.srem(key, member)
  91. return True
  92. except Exception as e:
  93. logging.warning("RedisDB.srem " + str(key) + " got exception: " + str(e))
  94. self.__open__()
  95. return False
  96. def smembers(self, key: str):
  97. try:
  98. res = self.REDIS.smembers(key)
  99. return res
  100. except Exception as e:
  101. logging.warning(
  102. "RedisDB.smembers " + str(key) + " got exception: " + str(e)
  103. )
  104. self.__open__()
  105. return None
  106. def zadd(self, key: str, member: str, score: float):
  107. try:
  108. self.REDIS.zadd(key, {member: score})
  109. return True
  110. except Exception as e:
  111. logging.warning("RedisDB.zadd " + str(key) + " got exception: " + str(e))
  112. self.__open__()
  113. return False
  114. def zcount(self, key: str, min: float, max: float):
  115. try:
  116. res = self.REDIS.zcount(key, min, max)
  117. return res
  118. except Exception as e:
  119. logging.warning("RedisDB.zcount " + str(key) + " got exception: " + str(e))
  120. self.__open__()
  121. return 0
  122. def zpopmin(self, key: str, count: int):
  123. try:
  124. res = self.REDIS.zpopmin(key, count)
  125. return res
  126. except Exception as e:
  127. logging.warning("RedisDB.zpopmin " + str(key) + " got exception: " + str(e))
  128. self.__open__()
  129. return None
  130. def zrangebyscore(self, key: str, min: float, max: float):
  131. try:
  132. res = self.REDIS.zrangebyscore(key, min, max)
  133. return res
  134. except Exception as e:
  135. logging.warning(
  136. "RedisDB.zrangebyscore " + str(key) + " got exception: " + str(e)
  137. )
  138. self.__open__()
  139. return None
  140. def transaction(self, key, value, exp=3600):
  141. try:
  142. pipeline = self.REDIS.pipeline(transaction=True)
  143. pipeline.set(key, value, exp, nx=True)
  144. pipeline.execute()
  145. return True
  146. except Exception as e:
  147. logging.warning(
  148. "RedisDB.transaction " + str(key) + " got exception: " + str(e)
  149. )
  150. self.__open__()
  151. return False
  152. def queue_product(self, queue, message, exp=settings.SVR_QUEUE_RETENTION) -> bool:
  153. for _ in range(3):
  154. try:
  155. payload = {"message": json.dumps(message)}
  156. pipeline = self.REDIS.pipeline()
  157. pipeline.xadd(queue, payload)
  158. # pipeline.expire(queue, exp)
  159. pipeline.execute()
  160. return True
  161. except Exception as e:
  162. logging.exception(
  163. "RedisDB.queue_product " + str(queue) + " got exception: " + str(e)
  164. )
  165. return False
  166. def queue_consumer(
  167. self, queue_name, group_name, consumer_name, msg_id=b">"
  168. ) -> Payload:
  169. try:
  170. group_info = self.REDIS.xinfo_groups(queue_name)
  171. if not any(e["name"] == group_name for e in group_info):
  172. self.REDIS.xgroup_create(queue_name, group_name, id="0", mkstream=True)
  173. args = {
  174. "groupname": group_name,
  175. "consumername": consumer_name,
  176. "count": 1,
  177. "block": 10000,
  178. "streams": {queue_name: msg_id},
  179. }
  180. messages = self.REDIS.xreadgroup(**args)
  181. if not messages:
  182. return None
  183. stream, element_list = messages[0]
  184. msg_id, payload = element_list[0]
  185. res = Payload(self.REDIS, queue_name, group_name, msg_id, payload)
  186. return res
  187. except Exception as e:
  188. if "key" in str(e):
  189. pass
  190. else:
  191. logging.exception(
  192. "RedisDB.queue_consumer "
  193. + str(queue_name)
  194. + " got exception: "
  195. + str(e)
  196. )
  197. return None
  198. def get_unacked_for(self, consumer_name, queue_name, group_name):
  199. try:
  200. group_info = self.REDIS.xinfo_groups(queue_name)
  201. if not any(e["name"] == group_name for e in group_info):
  202. return
  203. pendings = self.REDIS.xpending_range(
  204. queue_name,
  205. group_name,
  206. min=0,
  207. max=10000000000000,
  208. count=1,
  209. consumername=consumer_name,
  210. )
  211. if not pendings:
  212. return
  213. msg_id = pendings[0]["message_id"]
  214. msg = self.REDIS.xrange(queue_name, min=msg_id, count=1)
  215. _, payload = msg[0]
  216. return Payload(self.REDIS, queue_name, group_name, msg_id, payload)
  217. except Exception as e:
  218. if "key" in str(e):
  219. return
  220. logging.exception(
  221. "RedisDB.get_unacked_for " + consumer_name + " got exception: " + str(e)
  222. )
  223. self.__open__()
  224. def queue_info(self, queue, group_name) -> dict | None:
  225. try:
  226. groups = self.REDIS.xinfo_groups(queue)
  227. for group in groups:
  228. if group["name"] == group_name:
  229. return group
  230. except Exception as e:
  231. logging.warning(
  232. "RedisDB.queue_info " + str(queue) + " got exception: " + str(e)
  233. )
  234. return None
  235. REDIS_CONN = RedisDB()