python 注册 Nacos

根据项目需要 将python服务也纳入Nacos 中进行统一管理,所以进行python Nacos 项目适配。

记录本此适配过程。

python 安装不在说明。

系统版本:Linux 5.4.18-87.76-generic KYLINOS SMP Thu Aug 31 09:05:44 UTC 2023 aarch64 aarch64 aarch64 GNU/Linux

python 版本 :3.11.2

nacos-sdk-python :1.0.0

Nacos:2.3.0

1.安装 nacos-sdk-python

      pip  install   nacos-sdk-python

2. Nacos 注册

 NacosService.py

import nacos


class NacosService:

    def __init__(self,config):
        print(config)
        self.server_addresses = config["nacos_addr"]
        self.namespace =   config["namespace"]
        self.serviceName = config["serviceName"]
        self.ip =   config["ip"]
        self.port =   int(config["port"])
    def connect_service_center(self):
        self.client = nacos.NacosClient(self.server_addresses, namespace=self.namespace)
        print("Nacos Service Register  Start !")
        
    def register_instance(self):
        self.client.add_naming_instance(self.serviceName, self.ip, port=self.port)
        print("Nacos Service Register  Success !")

    def deregister_instance(self):
        self.client.remove_naming_instance(self.serviceName, self.ip, port=self.port)
        print("Nacos Service DeregisterInstance  Success !")
    
    def send_heartbeat(self):
        self.client.send_heartbeat(self.serviceName, self.ip, port=self.port)

3.集成 Flask 进行测试

TestNacos.py


from flask import Flask, request
import json
import uuid
import os
import threading
import time

import NacosManager
from utils.config import ConfigService

app = Flask(__name__)

@app.route('/hello', methods=['GET'])
def hello():
    if request.method == 'GET':
        code =200
        return_result = {'code': code, 'message': '处理成功', 'data': "hello"}
        return json.dumps(return_result, ensure_ascii=False)
        
  

def initNacos(serverConfig):
    nacosService= NacosManager.NacosService(serverConfig)
    nacosService.connect_service_center()
    nacosService.register_instance()
    while True:
        try:
            nacosService.send_heartbeat()
            time.sleep(20)
        except Exception as e:
            print(e)
            time.sleep(5)  
        
if __name__ == "__main__":
    serverConfig =ConfigService.readConfig()
    nacos_thread =threading.Thread(target=initNacos,args=(serverConfig,),daemon =True)
    nacos_thread.start()
    app.run(host="0.0.0.0", port=int(serverConfig["port"]), debug=True)

Nacos 因为需要一个线程专门来作为监听,所以开了一个线程在程序运行中 一直保持和注册中心通信,每20秒发送心跳。

3.读取配置

ConfigService.py

import json
import os

class ConfigService: 

    def readConfig():
        print(os.getcwd())
        filePath=os.path.join("config","Nacos.json")
        with open(filePath) as json_file:
            config = json.load(json_file)
        return  config   

Nacos.json

{
	"nacos_addr":"127.0.0.1:8848",
 "namespace":"Test-Nacos",
	"serviceName":"Test-Nacos-py"	,
	"clusterName":"DefaultCluster",
	"ip":"127.0.0.1",
	"port":9588
}

效果

Python Nacos 是一个 Python 客户端,用于与 Nacos 注册中心进行交互。Nacos 是一个开源的分布式系统服务发现、配置管理和服务管理平台。它可以帮助开发人员实现微服务架构中的服务注册和发现、配置管理等功能。 Python Nacos 提供了一个简单的接口,使得开发人员可以使用 Python 编写代码来与 Nacos 服务器进行交互。通过 Python Nacos,你可以轻松地从 Nacos 服务器中获取配置信息、注册服务、发现服务等操作。 如果你想在 Python 中使用 Nacos,可以使用 Python Nacos 客户端。你可以通过 pip 安装 Python Nacos: ``` pip install nacos-sdk-python ``` 安装完成后,你可以使用以下代码来连接到 Nacos 服务器: ```python from nacos import NacosClient client = NacosClient('localhost', namespace='test', username='nacos', password='nacos') ``` 这里我们指定了 Nacos 服务器的地址为 `localhost`,命名空间为 `test`,用户名为 `nacos`,密码为 `nacos`。你可以根据自己的实际情况进行修改。 接下来,你可以使用 Python Nacos 提供的 API 来与 Nacos 服务器进行交互。例如,你可以使用以下代码来获取一个配置项: ```python data_id = 'test' group = 'DEFAULT_GROUP' content = client.get_config(data_id, group) print(content) ``` 这里我们指定了配置项的 ID 为 `test`,组名为 `DEFAULT_GROUP`。`get_config` 方法会返回该配置项的内容。 除了获取配置项外,Python Nacos 还提供了注册服务、发现服务等功能。具体使用方法可以参考官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值