当前位置: 首页 > 工具软件 > Kazoo > 使用案例 >

Dubbo--kazoo库操作zk

缪志新
2023-12-01

从zk获取ip&port

  • 使用kazoo库链接zk,并从zk的节点中获取rpc节点数据字符串,从中获取已注册dubbo服务的的ip和端口
  • zoookeeper库也可以(我没调通,并且相关资料很少,不推荐)
from kazoo.client import KazooClient
from urllib.parse import unquote


zk_ip = '10.12.224.14'
zk_host = 2181
server_name = 'com.bjpowernode.dubbo.service.UserService'


zk = KazooClient(hosts=zk_ip + ':' + str(zk_host), read_only=True, timeout=30.0)
zk.start()
print(zk.state)

# 获取节点
print(zk.get_children('/'))
print(zk.get_children('/dubbo'))
print(zk.get_children('/dubbo/'+server_name))

# rpc
rpc_link = zk.get_children('/dubbo/' + server_name + '/providers')
print(rpc_link)

# url解码
rpc_link = unquote("".join(rpc_link))
print(rpc_link)

# 获取生产者ip端口
ip = rpc_link.split("/")[2].split(':')[0]
print(ip)
port = rpc_link.split("/")[2].split(':')[1]
print(port)

# 停止zkClient
zk.stop()

# 关闭连接
zk.close()
print(zk.state)

CONNECTED
['dubbo', 'zookeeper']
['com.bjpowernode.dubbo.service.UserService']
['consumers', 'configurators', 'routers', 'providers']
['dubbo%3A%2F%2F10.12.224.14%3A20880%2Fcom.bjpowernode.dubbo.service.UserService%3Fanyhost%3Dtrue%26application%3D007-zk-userservice-provider%26dubbo%3D2.6.2%26generic%3Dfalse%26interface%3Dcom.bjpowernode.dubbo.service.UserService%26methods%3DqueryUserById%26pid%3D44290%26revision%3D1.0.0%26side%3Dprovider%26timestamp%3D1614648799799']
dubbo://10.12.224.14:20880/com.bjpowernode.dubbo.service.UserService?anyhost=true&application=007-zk-userservice-provider&dubbo=2.6.2&generic=false&interface=com.bjpowernode.dubbo.service.UserService&methods=queryUserById&pid=44290&revision=1.0.0&side=provider&timestamp=1614648799799
10.12.224.14
20880
LOST

函数封装

from kazoo.client import KazooClient
from urllib.parse import unquote


def get_service_info_by_zk(zk_ip, dubbo_interface, zk_host=2181):
    """
    连接zk获取已注册服务的ip/port
    :param zk_ip:
    :param dubbo_interface:
    :param zk_host:
    :return: service_ip service_port
    """
    zk = KazooClient(hosts=zk_ip + ':' + str(zk_host), read_only=True, timeout=30.0)
    zk.start()
    try:
        rpc_link = zk.get_children('/dubbo/' + dubbo_interface + '/providers')
        rpc_link = unquote("".join(rpc_link))
        service_ip = rpc_link.split("/")[2].split(':')[0]
        service_port = rpc_link.split("/")[2].split(':')[1]
        return service_ip, service_port
    except Exception as e:
        raise e
    finally:
        zk.stop()
        zk.close()
 类似资料: