打赏

python连接consul

python连接consul

1. consul的KV操作

#!/usr/bin/python
# -*- coding: utf-8 -*-
# pip install python-consul
import consul


class Consul(object):
    def __init__(self, host, port, token):
        '''初始化,连接consul服务器'''
        self._consul = consul.Consul(host, port, token=token)

    def setConfig(self, key, value):
        self._consul.kv.put(key, value)

    def getConfig(self, key):
        index, data = self._consul.kv.get(key)
        print data['Value']

    def deletConfig(self, key):
        self._consul.kv.delete(key)


if __name__ == '__main__':
    host = "192.168.1.200"  # consul服务器的ip
    port = 8500  # consul服务器对外的端口
    token = "xxx"
    # 连接consul
    consul_client = Consul(host, port, token)
    # 设置值,会在根目录下,创建test目录
    consul_client.setConfig('test', 'ccc')
    # 获取值
    consul_client.getConfig('test')
    # 删除值
    consul_client.deletConfig('test')

2. consul服务注册

# -*- coding: UTF-8 -*-
# pip install python-consul
import consul


class Consul(object):
    def __init__(self, host, port, token):
        '''初始化,连接consul服务器'''
        self._consul = consul.Consul(host, port, token=token)

    def RegisterService(self, name, host, port, tags=None):
        tags = tags or []
        # 注册服务
        self._consul.agent.service.register(
            name,
            name,
            host,
            port,
            tags,
            # 健康检查ip端口,检查时间:5,超时时间:30,注销时间:30s
            check=consul.Check().tcp(host, port, "5s", "30s", "30s"))

    def GetService(self, name):
        services = self._consul.agent.services()
        service = services.get(name)
        if not service:
            return None, None
        addr = "{0}:{1}".format(service['Address'], service['Port'])
        return service, addr


if __name__ == '__main__':
    host = "192.168.1.120"  # consul服务器的ip
    port = "8500"  # consul服务器对外的端口
    token = "xxxx"
    consul_client = Consul(host, port, token)

    name = "loginservice"
    host = "192.168.1.10"
    port = 8500
    consul_client.RegisterService(name, host, port)

    check = consul.Check().tcp(host, port, "5s", "30s", "30s")
    print(check)
    res = consul_client.GetService("loginservice")
    print(res)

相关链接

https://www.cnblogs.com/angelyan/p/11157176.html

https://www.jb51.net/article/207263.htm

https://www.shuzhiduo.com/A/kjdw0OKOzN/

https://www.shuzhiduo.com/topic/python-consul配置中心/

posted @ 2021-09-02 15:32  苍山落暮  阅读(852)  评论(0)    收藏  举报