-
Notifications
You must be signed in to change notification settings - Fork 152
Description
nacos 服务端版本 2.5.1 / 3.0.2
nacos 客户端版本 nacos-python-sdk V2.0.8
现象:相同的代码 在 windows pycharm 运行时,服务正常注册且连接正常不掉线,在 Ubuntu 20.04 conda 3.11 环境中跑,服务正常连接会出现掉线情况
问题探索:尝试 开异步线程循环调用 naming_client.server_health() 方法
发现:windows 版本下可以正常调用,linux 版本下首次调用正常,后续会卡住
附录:
代码:
import asyncio
import uvicorn
from fastapi import FastAPI
from v2.nacos import ClientConfigBuilder, GRPCConfig, NacosConfigService, ConfigParam, NacosNamingService,
RegisterInstanceParam
app = FastAPI()
async def service_discovery(nacos_ip,nacos_port,nacos_user,nacos_password,nacos_namespace,service_name,host,port):
client_config = (
ClientConfigBuilder()
.username(nacos_user)
.password(nacos_password)
.server_address(nacos_ip+":"+str(nacos_port))
.namespace_id(nacos_namespace)
.build()
)
naming_client = await NacosNamingService.create_naming_service(client_config)
# 1. 注册服务实例
await naming_client.register_instance(
RegisterInstanceParam(
service_name=service_name,
ip=host,
port=port,
cluster_name="DEFAULT",
ephemeral=True, # 临时实例
metadata={"version": "1.0"}
)
)
print(f"服务注册成功: {service_name}@{nacos_ip}:{nacos_port}")
# 创建停止事件
stop_event = asyncio.Event()
# 启动健康检查循环(作为后台任务)
health_task = asyncio.create_task(health_check_loop(naming_client, stop_event))
async def health_check_loop(naming_client, stop_event: asyncio.Event = None):
"""
每3秒循环调用一次 naming_client.server_health() 方法
Args:
naming_client: 命名客户端实例
stop_event: 用于停止循环的事件标志
"""
while not stop_event.is_set() if stop_event else True:
try:
# 调用 server_health 方法
result = await naming_client.server_health()
print(f"Health check result: {result}")
except Exception as e:
# 处理可能的异常
print(f"Health check failed: {e}")
# 等待3秒,同时检查停止信号
try:
await asyncio.wait_for(stop_event.wait(), timeout=3.0) if stop_event else await asyncio.sleep(3)
break # 如果等待被中断,说明收到了停止信号
except asyncio.TimeoutError:
# 正常的3秒等待结束,继续下一次循环
continue
if name == 'main':
# 服务注册
asyncio.run(service_discovery("192.168.10.206","8848","nacos","Supcon_21","a12d638e-b022-4f14-b42e-d9935254f166","connect","192.168.10.207","62260"))
print(f"服务配置信息 host:192.168.10.207,port:62260")
uvicorn.run(app=app, host="192.168.10.207", port=62260, log_level="info")

