• Python 集成 Nacos 配置中心


    Python 集成 Nacos 配置中心

    下载 Nacos 官方 pyhton 库

    pip install nacos-sdk-python
    # 指定国内阿里云镜像源
    pip3 install nacos-sdk-python -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
    
    • 1
    • 2
    • 3

    配置 Nacos 相关信息

    Global:
      nacos:
        port: '8848'
        ip: '127.0.0.1'
        username: 'nacos'
        password: '123456'
        namespace: 'test'
        group: 'test'
        data_id: 'test'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 这里通过 env.yaml 指定相关配置信息定义环境变量配置文件

    代码逻辑

    from nacos import NacosClient
    import yaml
    import os
    import json
    
    
    
    # 使用 pyyaml 模块,把从配置中心获取的 yaml 数据转为 json 数据
    def get_config():
        config = load_config('../config/env.yaml')
        client = NacosClient(config['Global']['nacos']['ip'] + ':' + config['Global']['nacos']['port'],
                             namespace=config['Global']['nacos']['namespace'],
                             username=config['Global']['nacos']['username'],
                             password=config['Global']['nacos']['password'])
        data_id = config['Global']['nacos']['data_id']
        group = config['Global']['nacos']['group']
        config_info = client.get_config(data_id, group)
        if isinstance(config_info,bytes):
            str_config_info = config_info.decode()
        else:
            str_config_info = config_info
        dict_config_info = yaml.load(str_config_info,Loader=yaml.FullLoader)
        json_data = json.dumps(dict_config_info)
        print(json_data)
        return json_data
    
    
    # 加载 yaml 文件里的信息
    def load_config(file_path):
        """
        Load config from yml/yaml file.
        Args:
            file_path (str): Path of the config file to be loaded.
        Returns: global config
        """
        _, ext = os.path.splitext(file_path)
        assert ext in ['.yml', '.yaml'], "only support yaml files for now"
        config = yaml.load(open(file_path, 'rb'), Loader=yaml.Loader)
        return config
    
    # 测试
    if __name__ == '__main__':
        get_config()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    运行结果

    • Nacos 控制台配置文件内容

    在这里插入图片描述

    • 获取的 Nacos 中的配置信息

    在这里插入图片描述

  • 相关阅读:
    线性表的定义和基本操作
    MongoDB Realm数据库在Node中的使用
    牛客小白月赛 78
    Vue模板语法(下)
    中医自学平台---前端网站
    25G、50G、100G以太网介绍,网络工程师收藏!
    rxjava2源码分析
    超五类网线和六类网线的相同点和区别
    openXBOW的使用(2)
    Backup: MML shutdown 忽略
  • 原文地址:https://blog.csdn.net/Greenarrow961224/article/details/134461660