是因为nacos有个心跳机制,一个服务注册了以后,如果15秒内没人请求它,就认为这个服务不健康,就会变成红色,30秒内没人请求就会把它删了,需要写个心跳机制,比如每5秒请求一下它,保证它一直健康。找到的 python 代码如下,找不到原文了,如有问题请随时联系我:
import json
import requests
import time
NACOS_IP = "192.168.#.#" #你自己的nacos ip
NACOS_PORT = '8848'
NACOS_GROUP = 'default_group'
NACOS_NAME_SPACE='###' #你自己的namespace id
SERV_NAME = 'your service name'
SERV_IP = '192.168.your service ip'
SERV_PORT = 'your service port '
def create_instance():
create_instance_url = 'http://'+NACOS_IP+':'+NACOS_PORT+'/nacos/v1/ns/instance?healthy=true&port='+SERV_PORT+'&ip='+SERV_IP+'&groupName='+NACOS_GROUP+'&serviceName='+SERV_NAME+'&namespaceId='+NACOS_NAME_SPACE
response = requests.post(create_instance_url)
print('创建实例请求返回'+response.text)
def beat():
beat_info = {
'ip': SERV_IP,
'port': SERV_PORT,
'serviceName': SERV_NAME
}
beat_url = 'http://'+NACOS_IP+':'+NACOS_PORT+'/nacos/v1/ns/instance/beat?serviceName='+SERV_NAME+'&beat='+json.dumps(beat_info)+'&serviceName='+SERV_NAME+'&port='+SERV_PORT+'&ip='+SERV_IP
while True:
response = requests.put(beat_url)
print('心跳请求返回:'+time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())+' '+response.text)
time.sleep(5)
def init():
create_instance()
beat()
if __name__=='__main__':
init()
把ip port 换成你自己的,直接运行即可。