tianyajum commited on
Commit
9ca76dd
·
1 Parent(s): a348131

【xxx】修正几秒后nacos服务消失问题:0.1.15 配合 Nacos 2.x BUG

Browse files
Files changed (3) hide show
  1. app/core/config.py +1 -1
  2. app/core/nacos.py +4 -1
  3. main.py +8 -2
app/core/config.py CHANGED
@@ -7,7 +7,7 @@ class Config:
7
  APP_ENV = os.getenv("APP_ENV", "development")
8
 
9
  # Server
10
- HOST = os.getenv("HOST", "0.0.0.0")
11
  PORT = int(os.getenv("PORT", 8181))
12
 
13
  # Nacos
 
7
  APP_ENV = os.getenv("APP_ENV", "development")
8
 
9
  # Server
10
+ HOST = os.getenv("HOST", "127.0.0.1")
11
  PORT = int(os.getenv("PORT", 8181))
12
 
13
  # Nacos
app/core/nacos.py CHANGED
@@ -33,7 +33,10 @@ class NacosManager:
33
 
34
  def register_service(self):
35
  try:
36
- self.client.add_naming_instance(self.service_name, self.ip, self.port)
 
 
 
37
  logger.info(f"Registered service {self.service_name} at {self.ip}:{self.port}")
38
  except Exception as e:
39
  logger.error(f"Failed to register service: {e}")
 
33
 
34
  def register_service(self):
35
  try:
36
+ # 🔥【关键修复】必须手动指定这两个参数,否则 0.1.15 配合 Nacos 2.x 必死
37
+ self.client.add_naming_instance(self.service_name, self.ip, self.port,cluster_name="DEFAULT",
38
+ heartbeat_interval=5, # <--- 加在这里!强制定义心跳间隔
39
+ ephemeral=True)
40
  logger.info(f"Registered service {self.service_name} at {self.ip}:{self.port}")
41
  except Exception as e:
42
  logger.error(f"Failed to register service: {e}")
main.py CHANGED
@@ -12,6 +12,9 @@ import asyncio
12
  logging.basicConfig(level=logging.INFO)
13
  logger = logging.getLogger(__name__)
14
 
 
 
 
15
  @asynccontextmanager
16
  async def lifespan(app: FastAPI):
17
  # Startup logic
@@ -21,8 +24,11 @@ async def lifespan(app: FastAPI):
21
  # Setup and connect MCP clients
22
  await setup_mcp_clients()
23
  # connect_clients needs to run after startup potentially or concurrency
24
- asyncio.create_task(connect_clients())
25
-
 
 
 
26
  yield
27
  # Shutdown logic
28
  logger.info("Agent shutting down...")
 
12
  logging.basicConfig(level=logging.INFO)
13
  logger = logging.getLogger(__name__)
14
 
15
+ # 定义一个全局集合,用来存放后台任务的引用,防止被 GC
16
+ background_tasks = set()
17
+
18
  @asynccontextmanager
19
  async def lifespan(app: FastAPI):
20
  # Startup logic
 
24
  # Setup and connect MCP clients
25
  await setup_mcp_clients()
26
  # connect_clients needs to run after startup potentially or concurrency
27
+ task = asyncio.create_task(connect_clients())
28
+ background_tasks.add(task)
29
+ # 当任务完成时,自动从集合中移除,避免内存泄漏
30
+ task.add_done_callback(background_tasks.discard)
31
+
32
  yield
33
  # Shutdown logic
34
  logger.info("Agent shutting down...")