redis_connection.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. # !/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. '''
  4. @Project : lq-agent-api
  5. @File :redis_connection.py.py
  6. @IDE :PyCharm
  7. @Author :
  8. @Date :2025/7/21 15:07
  9. '''
  10. import redis # 同步专用
  11. # 尝试导入异步Redis模块
  12. try:
  13. from redis import asyncio as redis_asyncio
  14. except ImportError:
  15. try:
  16. import aioredis as redis_asyncio
  17. except ImportError:
  18. raise ImportError("Neither redis.asyncio nor aioredis is available. Please install 'redis[asyncio]' or 'aioredis'")
  19. # 导入Redis异常类
  20. from redis.exceptions import ConnectionError as redis_ConnectionError
  21. from typing import Optional, Protocol, Dict, Any, Set, Tuple
  22. from functools import wraps
  23. import asyncio
  24. from foundation.base.redis_config import RedisConfig
  25. from foundation.base.redis_config import load_config_from_env
  26. from foundation.logger.loggering import server_logger
  27. from typing import Dict, Any, List, Tuple
  28. from langchain_community.storage import RedisStore
  29. def with_redis_retry(max_retries: int = 3, delay: float = 1.0):
  30. """
  31. Redis操作重连装饰器
  32. Args:
  33. max_retries: 最大重试次数,默认3次
  34. delay: 重试间隔秒数,默认1秒
  35. """
  36. def decorator(func):
  37. @wraps(func)
  38. async def wrapper(self, *args, **kwargs):
  39. last_exception = None
  40. for attempt in range(max_retries + 1): # +1 包含第一次尝试
  41. try:
  42. return await func(self, *args, **kwargs)
  43. except (ConnectionResetError, redis_ConnectionError) as e:
  44. last_exception = e
  45. if attempt < max_retries:
  46. server_logger.warning(
  47. f"Redis连接异常 (尝试 {attempt + 1}/{max_retries + 1}): {str(e)}"
  48. )
  49. # 尝试重连
  50. try:
  51. await self._reconnect()
  52. except Exception as reconnect_error:
  53. server_logger.error(f"Redis重连失败: {str(reconnect_error)}")
  54. # 如果重连失败,继续重试
  55. await asyncio.sleep(delay * (attempt + 1)) # 指数退避
  56. continue
  57. server_logger.info(f"Redis重连成功,重新执行操作")
  58. await asyncio.sleep(delay) # 等待连接稳定
  59. else:
  60. server_logger.error(f"Redis操作失败,已达最大重试次数: {str(e)}")
  61. break
  62. except Exception as e:
  63. # 非连接相关的异常直接抛出
  64. raise e
  65. # 所有重试都失败了
  66. raise last_exception
  67. return wrapper
  68. return decorator
  69. class RedisConnection(Protocol):
  70. """
  71. Redis 接口协议
  72. """
  73. async def get(self, key: str) -> Any: ...
  74. async def set(self, key: str, value: Any, ex: Optional[int] = None, nx: bool = False) -> bool: ...
  75. async def hget(self, key: str, field: str) -> Any: ...
  76. async def hset(self, key: str, field: str, value: Any) -> int: ...
  77. async def hmset(self, key: str, mapping: Dict[str, Any]) -> bool: ...
  78. async def hgetall(self, key: str) -> Dict[str, Any]: ...
  79. async def delete(self, *keys: str) -> int: ...
  80. async def exists(self, key: str) -> int: ...
  81. async def expire(self, key: str, seconds: int) -> bool: ...
  82. async def scan(self, cursor: int, match: Optional[str] = None, count: Optional[int] = None) -> tuple[
  83. int, list[str]]: ...
  84. async def eval(self, script: str, keys: list[str], args: list[str]) -> Any: ...
  85. # 集合操作方法
  86. async def sadd(self, key: str, *values: str) -> int: ...
  87. async def scard(self, key: str) -> int: ...
  88. async def srem(self, key: str, *values: str) -> int: ...
  89. async def smembers(self, key: str) -> Set[str]: ...
  90. async def close(self) -> None: ...
  91. class RedisAdapter(RedisConnection):
  92. """
  93. Redis 适配器
  94. """
  95. def __init__(self, config: RedisConfig):
  96. self.config = config
  97. # 用于普通Redis 操作存储
  98. self._redis = None
  99. # 用于 langchain RedisStore 存储
  100. self._langchain_redis_client = None
  101. async def connect(self):
  102. """创建Redis连接"""
  103. # 简化的TCP Keep-Alive配置(兼容Windows系统)
  104. socket_options = {
  105. 'socket_keepalive': True,
  106. 'socket_connect_timeout': 10, # 连接超时10秒
  107. 'socket_timeout': 30, # 读写超时30秒
  108. }
  109. # 使用新版本的redis.asyncio
  110. self._redis = redis_asyncio.from_url(
  111. self.config.url,
  112. password=self.config.password,
  113. db=self.config.db,
  114. encoding="utf-8",
  115. decode_responses=True,
  116. max_connections=self.config.max_connections,
  117. **socket_options
  118. )
  119. # 用于 langchain RedisStore 存储
  120. # 必须设为 False(LangChain 需要 bytes 数据)
  121. self._langchain_redis_client = redis_asyncio.from_url(
  122. self.config.url,
  123. password=self.config.password,
  124. db=self.config.db,
  125. encoding="utf-8",
  126. decode_responses=False,
  127. max_connections=self.config.max_connections,
  128. **socket_options
  129. )
  130. # ✅ 使用同步 Redis 客户端
  131. # self._langchain_redis_client = redis.Redis.from_url(
  132. # self.config.url,
  133. # password=self.config.password,
  134. # db=self.config.db,
  135. # decode_responses=False, # LangChain 需要 bytes
  136. # )
  137. #错误:Expected Redis client, got Redis instead
  138. # self._langchain_redis_client = async_redis.from_url(
  139. # self.config.url,
  140. # password=self.config.password,
  141. # db=self.config.db,
  142. # decode_responses=False
  143. # )
  144. return self
  145. @with_redis_retry()
  146. async def get(self, key: str) -> Any:
  147. """获取Redis键值"""
  148. return await self._redis.get(key)
  149. @with_redis_retry()
  150. async def set(self, key: str, value: Any, ex: Optional[int] = None, nx: bool = False) -> bool:
  151. """设置Redis键值"""
  152. return await self._redis.set(key, value, ex=ex, nx=nx)
  153. @with_redis_retry()
  154. async def setex(self, key: str, time: int, value: Any) -> bool:
  155. """设置Redis键值并指定过期时间"""
  156. return await self._redis.setex(key, time, value)
  157. @with_redis_retry()
  158. async def hget(self, key: str, field: str) -> Any:
  159. return await self._redis.hget(key, field)
  160. @with_redis_retry()
  161. async def hset(self, key: str, field: str, value: Any) -> int:
  162. return await self._redis.hset(key, field, value)
  163. @with_redis_retry()
  164. async def hmset(self, key: str, mapping: Dict[str, Any]) -> bool:
  165. return await self._redis.hmset(key, mapping)
  166. @with_redis_retry()
  167. async def hgetall(self, key: str) -> Dict[str, Any]:
  168. return await self._redis.hgetall(key)
  169. @with_redis_retry()
  170. async def delete(self, *keys: str) -> int:
  171. return await self._redis.delete(*keys)
  172. @with_redis_retry()
  173. async def exists(self, key: str) -> int:
  174. return await self._redis.exists(key)
  175. @with_redis_retry()
  176. async def expire(self, key: str, seconds: int) -> bool:
  177. return await self._redis.expire(key, seconds)
  178. @with_redis_retry()
  179. async def scan(self, cursor: int, match: Optional[str] = None, count: Optional[int] = None) -> tuple[
  180. int, list[str]]:
  181. return await self._redis.scan(cursor, match=match, count=count)
  182. @with_redis_retry()
  183. async def eval(self, script: str, numkeys: int, *keys_and_args: str) -> Any:
  184. """执行Redis脚本"""
  185. return await self._redis.eval(script, numkeys, *keys_and_args) # 解包成独立参数
  186. # 集合操作方法实现
  187. @with_redis_retry()
  188. async def sadd(self, key: str, *values: str) -> int:
  189. """向集合添加成员,返回添加的成员数量"""
  190. return await self._redis.sadd(key, *values)
  191. @with_redis_retry()
  192. async def scard(self, key: str) -> int:
  193. """获取集合成员数量"""
  194. return await self._redis.scard(key)
  195. @with_redis_retry()
  196. async def srem(self, key: str, *values: str) -> int:
  197. """从集合删除成员,返回删除的成员数量"""
  198. return await self._redis.srem(key, *values)
  199. @with_redis_retry()
  200. async def smembers(self, key: str) -> Set[str]:
  201. """获取集合所有成员"""
  202. return await self._redis.smembers(key)
  203. def get_langchain_redis_client(self):
  204. return self._langchain_redis_client
  205. async def _reconnect(self) -> None:
  206. """重新连接Redis"""
  207. try:
  208. server_logger.info("正在重新连接Redis...")
  209. if self._redis:
  210. await self._redis.close()
  211. await self._redis.wait_closed()
  212. if self._langchain_redis_client:
  213. await self._langchain_redis_client.close()
  214. await self._langchain_redis_client.wait_closed()
  215. # 等待短暂时间后重连
  216. await asyncio.sleep(1)
  217. # 重新建立连接
  218. await self.connect()
  219. server_logger.info("Redis重连成功")
  220. except Exception as e:
  221. server_logger.error(f"Redis重连失败: {str(e)}")
  222. raise
  223. async def close(self) -> None:
  224. if self._redis:
  225. await self._redis.close()
  226. #await self._redis.wait_closed() #该方法已弃用
  227. if self._langchain_redis_client:
  228. await self._langchain_redis_client.close()
  229. #await self._langchain_redis_client.wait_closed()
  230. class RedisConnectionFactory:
  231. """
  232. redis 连接工厂函数
  233. """
  234. _connections: Dict[str, RedisConnection] = {}
  235. _stores: Dict[str, RedisStore] = {}
  236. @classmethod
  237. async def get_connection(cls) -> RedisConnection:
  238. """获取Redis连接(单例模式)"""
  239. # 加载配置
  240. redis_config = load_config_from_env()
  241. #server_logger.info(f"redis_config={redis_config}")
  242. # 使用配置参数生成唯一标识
  243. conn_id = f"{redis_config.url}-{redis_config.db}"
  244. if conn_id not in cls._connections:
  245. adapter = RedisAdapter(redis_config)
  246. await adapter.connect()
  247. cls._connections[conn_id] = adapter
  248. return cls._connections[conn_id]
  249. @classmethod
  250. async def get_redis_store(cls) -> RedisStore:
  251. """获取 LangChain RedisStore 实例"""
  252. # 加载配置
  253. redis_config = load_config_from_env()
  254. conn = await cls.get_connection() # 或通过其他方式获取
  255. client = conn.get_langchain_redis_client()
  256. return client
  257. @classmethod
  258. async def get_langchain_redis_store(cls) -> RedisStore:
  259. """获取 LangChain RedisStore 实例
  260. 目前该方法存在问题
  261. """
  262. # 加载配置
  263. redis_config = load_config_from_env()
  264. # 使用配置参数生成唯一标识
  265. store_id = f"{redis_config.url}-{redis_config.db}"
  266. if store_id not in cls._stores:
  267. conn = await cls.get_connection() # 或通过其他方式获取
  268. client = conn.get_langchain_redis_client()
  269. store = client
  270. server_logger.info(f"client={client}")
  271. server_logger.info(f"store={dir(store)}")
  272. cls._stores[store_id] = store
  273. return cls._stores[store_id]
  274. @classmethod
  275. async def close_all(cls):
  276. """关闭所有Redis连接"""
  277. for conn in cls._connections.values():
  278. await conn.close()
  279. cls._connections = {}
  280. @classmethod
  281. def get_connection_count(cls) -> int:
  282. """获取当前连接数"""
  283. return len(cls._connections)