redis_utils.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import json
  2. import time
  3. import asyncio
  4. import sys
  5. from pathlib import Path
  6. # root_dir = Path(__file__).parent.parent.parent
  7. # print(root_dir)
  8. from typing import Dict, Optional, Any
  9. from foundation.observability.monitoring.time_statistics import track_execution_time
  10. from foundation.infrastructure.config import config_handler
  11. from foundation.observability.logger.loggering import server_logger
  12. from foundation.infrastructure.cache.redis_connection import RedisConnectionFactory
  13. # 缓存数据有效期 默认 3 分钟
  14. CACHE_DATA_EXPIRED_TIME = 3 * 60
  15. async def set_redis_result_cache_data(data_type: str , trace_id: str, value: str):
  16. """
  17. 设置redis结果缓存数据
  18. @param data_type: 数据类型,基本信息 cattle_info、体温信息 cattle_temperature 、步数信息 cattle_walk
  19. @param trace_id: 链路跟踪ID
  20. @param value: 缓存数据
  21. """
  22. expired_time = config_handler.get("api", "CACHE_DATA_EXPIRED_TIME" , CACHE_DATA_EXPIRED_TIME)
  23. key = f"{trace_id}:{data_type}"
  24. # 直接获取 RedisStore
  25. redis_store = await RedisConnectionFactory.get_redis_store()
  26. await redis_store.set(key, value , ex=expired_time)
  27. async def get_redis_result_cache_data(data_type: str , trace_id: str):
  28. """
  29. 获取redis结果缓存数据
  30. @param data_type: 数据类型,基本信息 cattle_info、体温信息 cattle_temperature 、步数信息 cattle_walk
  31. @param trace_id: 链路跟踪ID
  32. """
  33. key = f"{trace_id}:{data_type}"
  34. # 直接获取 RedisStore
  35. redis_store = await RedisConnectionFactory.get_redis_store()
  36. value = await redis_store.get(key)
  37. value = value.decode('utf-8')
  38. return value
  39. async def get_redis_result_cache_data_and_delete_key(data_type: str , trace_id: str):
  40. """
  41. 获取redis结果缓存数据
  42. @param data_type: 数据类型,基本信息 cattle_info、体温信息 cattle_temperature 、步数信息 cattle_walk
  43. @param trace_id: 链路跟踪ID
  44. """
  45. key = f"{trace_id}:{data_type}"
  46. # 直接获取 RedisStore
  47. redis_store = await RedisConnectionFactory.get_redis_store()
  48. value = await redis_store.get(key)
  49. server_logger.info(f"获取redis结果缓存数据: {key}-{value}")
  50. if value is None:
  51. return None
  52. # 第一步:转成字符串(decode)
  53. json_str = value.decode('utf-8')
  54. # 第二步:解析 JSON
  55. data = json.loads(json_str)
  56. # 删除key
  57. #await redis_store.delete(key)
  58. return data
  59. @track_execution_time
  60. async def store_file_info(file_id: str, file_info: Dict[str, Any], expire_seconds: int = 3600, force_update: bool = False) -> bool:
  61. """
  62. 存储文件信息(直接存储模式)
  63. Args:
  64. file_id: 文件ID
  65. file_info: 文件信息字典
  66. expire_seconds: 过期时间(秒),默认1小时
  67. force_update: 是否强制更新已存在的文件信息
  68. Returns:
  69. bool: 存储是否成功
  70. """
  71. try:
  72. redis_store = await RedisConnectionFactory.get_redis_store()
  73. # 检查是否已存在,如果存在则更新callback_task_id
  74. existing_meta = await redis_store.get(f"meta:{file_id}")
  75. if existing_meta:
  76. # 解析现有元数据
  77. existing_file_info = json.loads(existing_meta.decode('utf-8'))
  78. # 更新callback_task_id为最新的
  79. if 'callback_task_id' in file_info:
  80. existing_file_info['callback_task_id'] = file_info['callback_task_id']
  81. elif 'callback_task_id' not in existing_file_info:
  82. # 如果两者都没有callback_task_id,添加一个新的
  83. existing_file_info['callback_task_id'] = None
  84. # 并行更新meta和content的TTL,确保同步过期
  85. update_tasks = [
  86. redis_store.setex(f"meta:{file_id}", expire_seconds, json.dumps(existing_file_info))
  87. ]
  88. # 如果存在content,也需要更新其TTL以保持同步
  89. content_key = f"content:{file_id}"
  90. existing_content = await redis_store.get(content_key)
  91. if existing_content:
  92. update_tasks.append(redis_store.setex(content_key, expire_seconds, existing_content))
  93. server_logger.info(f"同步更新content的TTL: {content_key}")
  94. else:
  95. server_logger.warning(f"未找到content键,只更新meta TTL: {content_key}")
  96. # 执行并行更新
  97. await asyncio.gather(*update_tasks)
  98. server_logger.info(f"文件信息已存在,同步更新TTL: {file_id} -> {existing_file_info['callback_task_id']}")
  99. return True
  100. # 提取文件内容
  101. file_content = file_info.get('file_content')
  102. if file_content:
  103. file_size = len(file_content)
  104. server_logger.info(f"使用直接存储策略: {file_id}, {file_size/1024/1024:.2f}MB")
  105. # 直接存储
  106. metadata = {k: v for k, v in file_info.items() if k != 'file_content'}
  107. metadata['file_size'] = file_size
  108. # 并行执行元数据和内容存储以提高性能
  109. tasks = [
  110. redis_store.setex(f"meta:{file_id}", expire_seconds, json.dumps(metadata)),
  111. redis_store.setex(f"content:{file_id}", expire_seconds, file_content)
  112. ]
  113. await asyncio.gather(*tasks)
  114. else:
  115. # 没有文件内容,只存元数据
  116. metadata = file_info.copy()
  117. await redis_store.setex(f"meta:{file_id}", expire_seconds, json.dumps(metadata))
  118. server_logger.info(f"文件信息已存储到Redis: {file_id}")
  119. return True
  120. except Exception as e:
  121. server_logger.error(f"存储文件信息到Redis失败: {str(e)}")
  122. return False
  123. @track_execution_time
  124. async def get_file_info(file_id: str, include_content: bool = True) -> Optional[Dict[str, Any]]:
  125. """
  126. 根据file_id获取文件信息
  127. Args:
  128. file_id: 文件ID
  129. include_content: 是否包含文件内容(默认True),可选False以提高效率
  130. Returns:
  131. Dict: 文件信息字典,如果不存在返回None
  132. """
  133. try:
  134. redis_store = await RedisConnectionFactory.get_redis_store()
  135. # 获取元数据
  136. meta_key = f"meta:{file_id}"
  137. meta_bytes = await redis_store.get(meta_key)
  138. if not meta_bytes:
  139. server_logger.warning(f"文件元数据不存在: {meta_key}")
  140. return None
  141. # 解析元数据
  142. file_info = json.loads(meta_bytes.decode('utf-8'))
  143. # 根据存储类型获取文件内容
  144. if include_content and 'file_size' in file_info:
  145. # 直接获取文件内容
  146. content_key = f"content:{file_id}"
  147. file_content = await redis_store.get(content_key)
  148. if file_content:
  149. file_info['file_content'] = file_content
  150. else:
  151. server_logger.warning(f"文件内容不存在: {content_key}")
  152. return None # 文件内容缺失,返回None
  153. server_logger.info(f"从Redis获取到文件信息: {meta_key}")
  154. return file_info
  155. except json.JSONDecodeError as e:
  156. server_logger.error(f"解析文件元数据JSON失败: {str(e)}")
  157. return None
  158. except Exception as e:
  159. server_logger.error(f"获取文件信息失败: {str(e)}")
  160. return None
  161. async def delete_file_info(file_id: str) -> bool:
  162. """
  163. 删除文件信息
  164. Args:
  165. file_id: 文件ID
  166. Returns:
  167. bool: 删除是否成功
  168. """
  169. try:
  170. # 为了避免事件循环冲突,直接创建新的Redis连接
  171. from foundation.infrastructure.cache.redis_config import load_config_from_env
  172. from foundation.infrastructure.cache.redis_connection import RedisAdapter
  173. redis_config = load_config_from_env()
  174. adapter = RedisAdapter(redis_config)
  175. await adapter.connect()
  176. redis_store = adapter.get_langchain_redis_client()
  177. # 获取元数据以确定存储类型
  178. meta_key = f"meta:{file_id}"
  179. meta_bytes = await redis_store.get(meta_key)
  180. if not meta_bytes:
  181. server_logger.warning(f"文件元数据不存在: {meta_key}")
  182. # 清理连接
  183. await adapter.close()
  184. return True # 可能已经删除了
  185. # 解析元数据
  186. file_info = json.loads(meta_bytes.decode('utf-8'))
  187. # 删除相应的内容
  188. deleted_count = 0
  189. # 删除元数据
  190. deleted_count += await redis_store.delete(meta_key)
  191. # 如果有文件大小信息,说明有文件内容,需要删除
  192. if 'file_size' in file_info:
  193. # 删除文件内容
  194. content_key = f"content:{file_id}"
  195. deleted_count += await redis_store.delete(content_key)
  196. if deleted_count > 0:
  197. server_logger.info(f"已删除文件信息: {file_id}, {deleted_count}个键")
  198. else:
  199. server_logger.warning(f"Redis缓存不存在,无法删除: {file_id}")
  200. # 清理连接
  201. await adapter.close()
  202. return True if deleted_count > 0 else False
  203. except json.JSONDecodeError as e:
  204. server_logger.error(f"解析文件元数据JSON失败: {str(e)}")
  205. # 清理连接
  206. await adapter.close()
  207. return False
  208. except Exception as e:
  209. server_logger.error(f"删除文件信息失败: {str(e)}")
  210. # 清理连接
  211. await adapter.close()
  212. return False
  213. finally:
  214. # 确保连接被关闭
  215. await adapter.close()
  216. #asyncio.run(delete_file_info('e385049cde7d21a48c7de216182f0f23'))