Python registers microservices in nacos

Install

First you need to install the nacos sdk of python
pip install nacos-sdk-python

register

The registration process is very simple. It should be noted that heartbeats must be sent regularly after registration, otherwise the service will be deletednacos.

import nacos
import time

SERVER_ADDRESSES = "http://1.2.3.4:8848"  # Nacos服务器地址
NAMESPACE = "6c40f203-746a-ff37d4d41601"  # Nacos的命名空间ID

# 获取Nacos客户端
client = nacos.NacosClient(SERVER_ADDRESSES, namespace=NAMESPACE, username="nacos", password="nacos")

# 服务注册
client.add_naming_instance("py-demo", "1.2.3.4", port=8888)


while True:
    try:
        client.send_heartbeat("py-demo", "1.2.3.4", port=8888)
        time.sleep(30)
    except Exception as e:
        print(f"Error: {e}")
        time.sleep(5)  # 在尝试重新发送心跳之前稍作延迟

Guess you like

Origin blog.csdn.net/majiayu000/article/details/133951754