Nacos 是阿里巴巴开源的动态服务发现、配置管理和服务管理平台,支持多种语言客户端。以下是在 Python 中使用 Nacos 的完整方案:
一、安装客户端
推荐使用官方维护的 nacos-sdk-python
库:
bash
pip install nacos-sdk-python
二、基础配置
创建配置文件 nacos_config.py
:
python
NACOS_SERVER = "http://localhost:8848" # Nacos服务器地址
NAMESPACE = "public" # 命名空间
GROUP = "DEFAULT_GROUP" # 配置分组
SERVICE_NAME = "python-service" # 服务名称
DATA_ID = "app-config" # 配置标识
三、服务注册与发现
服务注册(以FastAPI为例)
python
from nacos import NacosClient
from nacos_config import *
from fastapi import FastAPI
app = FastAPI()
client = NacosClient(NACOS_SERVER, namespace=NAMESPACE)
@app.on_event("startup")
def register_service():
client.add_naming_instance(
service_name=SERVICE_NAME,
ip="127.0.0.1",
port=8000,
metadata={"version": "1.0", "env": "prod"}
)
print("服务注册成功")
@app.on_event("shutdown")
def deregister_service():
client.remove_naming_instance(SERVICE_NAME, "127.0.0.1", 8000)
print("服务注销完成")
服务发现
python
def discover_service():
instances = client.list_naming_instance(SERVICE_NAME)
return [{"ip": inst["ip"], "port": inst["port"]} for inst in instances["hosts"]]
# 调用示例
print("当前可用实例:", discover_service())
四、配置管理
获取配置
python
config = client.get_config(DATA_ID, GROUP)
print("当前配置:", config)
动态配置监听
python
def config_change_callback(config):
print("配置已更新:", config["content"])
# 更新应用配置(示例:更新全局变量)
global app_config
app_config = config["content"]
# 添加监听
client.add_config_watcher(
data_id=DATA_ID,
group=GROUP,
cb=config_change_callback
)
发布配置
python
new_config = {"db_url": "mysql://new_host:3306", "timeout": 30}
client.publish_config(
data_id=DATA_ID,
group=GROUP,
content=str(new_config)
)
五、高级功能
心跳检测(维持服务健康状态)
python
import threading
import time
def heartbeat():
while True:
client.send_beat(SERVICE_NAME, "127.0.0.1", 8000)
time.sleep(5) # 每5秒发送一次心跳
threading.Thread(target=heartbeat, daemon=True).start()
集成认证
python
client = NacosClient(
server_addresses=NACOS_SERVER,
namespace=NAMESPACE,
username="nacos", # 认证用户名
password="nacos123" # 认证密码
)
六、生产环境建议
-
高可用部署:配置多个Nacos服务器地址
pythonclient = NacosClient("192.168.1.10:8848,192.168.1.11:8848")
-
错误重试:添加重试机制
pythonfrom tenacity import retry, stop_after_attempt @retry(stop=stop_after_attempt(3)) def reliable_register(): client.add_naming_instance(...)
-
配置加密:敏感配置使用Nacos的加密功能
pythonclient.publish_config(encrypted_content="K8s#123!@", encrypted=True)
-
监控集成:接入Prometheus监控
pythonfrom prometheus_client import Gauge SERVICE_COUNT = Gauge('nacos_services', 'Number of registered services') SERVICE_COUNT.set(len(discover_service()))
七、调试技巧
-
查看Nacos控制台:http://localhost:8848/nacos
-
日志排查:
pythonimport logging logging.basicConfig(level=logging.DEBUG)
-
版本兼容性检查:
bashpip show nacos-sdk-python # 确保版本≥0.5.0(支持Nacos 2.x)
通过以上方案,您可以实现:
- 服务自动注册与发现
- 配置动态更新与回滚
- 服务健康监测与故障转移
- 灰度发布与流量管理
建议参考官方文档获取最新特性:https://nacos.io/zh-cn/docs/other-language.html