Parcourir la source

缓存功能修改,连接233服务器

wangjiaojiao il y a 3 semaines
Parent
commit
2f16e2989f

+ 5 - 3
app/routers/health.py

@@ -20,9 +20,11 @@ PRETRAIN_MODELS: Dict[str, WindFarmPretrainModel] = {}  # 改为存储风场级
 REALTIME_ASSESSOR = HealthAssessor()
 # 新增缓存服务
 CACHE_SERVICE = CacheService(
-host='localhost', 
+host='192.168.50.233', 
 port=6379, 
-ttl=2592000 #单位秒 
+db =10,
+password=123456,
+ttl=None #单位秒 
 )  
 
 @router.on_event("startup")
@@ -144,7 +146,7 @@ async def assess_windfarm_optimized(request: AssessmentRequest):
                 CACHE_SERVICE.set_cached_response(
                     request_body,
                     cache_data,
-                    3600  # 缓存1小时
+                    None  # 缓存1小时
                 )
             except Exception as e:
                 logger.error(f"缓存设置失败: {str(e)}")    

+ 18 - 12
app/services/HealthCacheService.py

@@ -6,11 +6,11 @@ import redis
 from typing import Optional, Dict, Any
 
 class CacheService:
-    def __init__(self, host: str = 'localhost', port: int = 6379, 
-                 db: int = 0, password: str = None, ttl: int = 2592000):
+    def __init__(self, host: str = '192.168.50.233', port: int = 6379, 
+                 db: int = 10, password: int = 123456, ttl: Optional[int] = None):
         """
         初始化Redis缓存服务
-        :param ttl: 默认缓存时间(秒),默认24小时
+        :param ttl: 默认缓存时间(秒)
         """
         self.client = redis.Redis(
             host=host,
@@ -47,26 +47,32 @@ class CacheService:
             self.logger.error(f"获取缓存失败: {str(e)}")
             return None
     
+    
     def set_cached_response(self, request_body: Dict[str, Any], 
-                          response_data: Dict[str, Any], 
-                          ttl: int = None) -> bool:
+                        response_data: Dict[str, Any], 
+                        ttl: Optional[int] = None) -> bool:
         """
         设置缓存结果
+        :param ttl: 如果为 None 或 0,则永久缓存
         """
         cache_key = self._generate_cache_key(request_body)
         try:
             expire_time = ttl if ttl is not None else self.ttl
-            self.client.setex(
-                cache_key,
-                expire_time,
-                json.dumps(response_data)
-            )
-            self.logger.info(f"缓存已设置: {cache_key} (TTL: {expire_time}s)")
+            
+            if expire_time is None or expire_time <= 0:
+                # 永久缓存
+                self.client.set(cache_key, json.dumps(response_data))
+                self.logger.info(f"缓存已设置(永久): {cache_key}")
+            else:
+                # 带过期时间的缓存
+                self.client.setex(cache_key, expire_time, json.dumps(response_data))
+                self.logger.info(f"缓存已设置(TTL: {expire_time}s): {cache_key}")
+            
             return True
         except Exception as e:
             self.logger.error(f"设置缓存失败: {str(e)}")
             return False
-    
+
     def clear_cache(self, request_body: Dict[str, Any]) -> bool:
         """清除指定请求的缓存"""
         cache_key = self._generate_cache_key(request_body)

+ 1 - 1
app/services/HealthPretrain.py

@@ -18,7 +18,7 @@ class WindFarmPretrainModel:
         self.subsystem_models = {}  # 各子系统模型
         self.features = {}  # 各子系统使用的特征
         self.turbine_codes = []  # 包含的风机列表
-        self.cache_client = CacheService(host='localhost', port=6379)  # 添加缓存客户端        
+        self.cache_client = CacheService(host='192.168.50.233', port=6379,db =10,password=123456,ttl=2592000 )  # 添加缓存客户端     
     def train(self, data_dict: Dict[str, pd.DataFrame], mill_type: str):
         """训练风场模型(支持单特征子系统)"""
         self.mill_type = mill_type

+ 1 - 1
app/services/HealthTestRedis.py

@@ -2,7 +2,7 @@ from app.services.HealthCacheService import CacheService
 from app.logger import logger
 
 def test_redis_connection():
-    cache = CacheService(host='localhost', port=6379)
+    cache = CacheService(host='192.168.50.233', port=6379)
     if cache.ping():
         logger.info("Redis连接测试成功")