nacos-python/main.py

42 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# main.py
import uvicorn
from fastapi import FastAPI
from contextlib import asynccontextmanager
from nacos_client import NacosService
# Nacos 服务配置 这里指当前python服务的ip和端口
SERVICE_IP = "127.0.0.1" # 你的服务 IP 地址
SERVICE_PORT = 8089 # 你的服务端口
# 初始化 Nacos 服务
nacos_service = NacosService()
# 发现服务
instances = nacos_service.discover_service()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""生命周期管理,替代 startup/shutdown 事件"""
# 启动逻辑(相当于 on_event("startup")
nacos_service.register_service(ip=SERVICE_IP, port=SERVICE_PORT)
print("Service registered to Nacos on startup")
yield # 应用运行期间
# 关闭逻辑(相当于 on_event("shutdown")
nacos_service.deregister_service(ip=SERVICE_IP, port=SERVICE_PORT)
print("Service deregistered from Nacos on shutdown")
app = FastAPI(lifespan=lifespan) # 通过 lifespan 参数传递生命周期管理
@app.get("/")
async def read_root():
return {"message": "Hello, Nacos!"}
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=8089)