写一个 python daemo 注册到nacos中
""" 注册到nacos中的deamon nacos:2.3.2(模式:standalone) python:3.6.8 nohup python3 demon.py & """ import requests import threading import time # Nacos 服务器地址和端口 nacos_url = "http://127.0.0.1:8848" # Nacos 登录信息 username = "test" password = "123456" # 服务注册信息 service_name = "suyajun-service" ip = "127.0.0.1" port = 8080 # 登录 Nacos 获取 token def login_to_nacos(url, username, password): login_url = f"{url}/nacos/v1/auth/login" login_data = { "username": username, "password": password } response = requests.post(login_url, data=login_data) if response.status_code == 200: return response.json().get("accessToken") else: raise Exception(f"Failed to login to Nacos: {response.text}") # 注册服务到 Nacos def register_service(url, token, service_name, ip, port): register_url = f"{url}/nacos/v1/ns/instance" register_data = { "serviceName": service_name, "ip": ip, "port": port, "namespaceId": "public", # 这里使用 public 命名空间,如果有其他命名空间请替换 "groupName": "DEFAULT_GROUP", # 默认组名 "weight": 1.0, "enable": "true", "healthy": "true", "metadata": "{}", "ephemeral": "true", "accessToken": token } response = requests.post(register_url, params=register_data) if response.status_code == 200: print("Service registered successfully") else: raise Exception(f"Failed to register service: {response.status_code} - {response.text}") # 发送心跳信息到 Nacos def send_heartbeat(url, token, service_name, ip, port): while True: heartbeat_url = f"{url}/nacos/v1/ns/instance/beat" heartbeat_data = { "serviceName": service_name, "ip": ip, "port": port, "namespaceId": "public", # 这里使用 public 命名空间,如果有其他命名空间请替换 "groupName": "DEFAULT_GROUP", # 默认组名 "ephemeral": "true", "accessToken": token } response = requests.put(heartbeat_url, params=heartbeat_data) if response.status_code == 200: print("Heartbeat sent successfully") else: print(f"Failed to send heartbeat: {response.status_code} - {response.text}") # 每 5 秒发送一次心跳 time.sleep(5) # 主函数 def main(): try: # 登录获取 token token = login_to_nacos(nacos_url, username, password) print(f"Login successful, token: {token}") # 注册服务 register_service(nacos_url, token, service_name, ip, port) # 启动心跳线程 heartbeat_thread = threading.Thread(target=send_heartbeat, args=(nacos_url, token, service_name, ip, port)) heartbeat_thread.daemon = True heartbeat_thread.start() # 保持主线程运行 while True: time.sleep(1) except Exception as e: print(e) if __name__ == "__main__": main()