import uvicorn
from fastapi import FastAPI
app = FastAPI()
def register(server_name, ip, port):
c = consul.Consul(host="127.0.0.1", port=8500) # consul服务器信息
print(f"开始注册服务{server_name}")
check = consul.Check.tcp(ip, port, "10s") # 健康检查的ip,端口,检查间隔时间
result= c.agent.service.register(
name=server_name, # 应用名称
service_id="0d4b3555d221441bef23a35f3984532f", # 应用唯一标识,应用异常注销时需要用到
address=ip, # 应用IP
port=port, # 应用地址
check=check, # 应用服务信息
timeout=60 # 注册超时时间
)
if result:
print(f"注册服务{server_name}成功")
else:
print(f"注册服务{server_name}失败")
def unregister(service_id):
c = consul.Consul()
print(f"开始退出服务{service_id}")
result = c.agent.service.deregister(service_id=service_id)
if result:
print(f"注销服务{service_id}成功")
else:
print(f"注销服务{service_id}失败")
@app.on_event("startup")
async def startup_event():
register("user-service", "127.0.0.1", 8000)
@app.on_event("shutdown")
async def shutdown_event():
unregister("0d4b3555d221441bef23a35f3984532f")
if __name__ == '__main__':
uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True,
debug=True, workers=1)