以上转载于:https://blog.csdn.net/zuozewei/article/details/85333060
依赖库:kazoo和dubbo_telnet
kazoo是向zookeeper注册中心获取dubbo接口实例地址
telnet是用来连接实例进行接口调试
过程:查询实例地址,查询方法列表,设计传参发送请求
def get_dubbo_services(self):
global Host
zk = KazooClient(hosts="{}".format(Host))
zk.start()
urls = []
list = zk.get_children("dubbo")
for i in list:
if 'serv' in i: #关键字过滤
# print i
try:
gg = zk.get_children("/dubbo/{}/providers".format(i))
if gg:
for j in gg:
url = urllib.parse.unquote(j)
if url.startswith('dubbo:'):
urls.append(url.split('?')[0].split('dubbo://')[1])
except Exception as e:
print(e)
print(i)
services = {}
for i in urls:
try:
path, service = i.split('/')
if not services.get(path):
services.update({path: []})
services[path].append(service)
except Exception as e:
pass
zk.stop()
print(json.dumps(services, indent=4))
def get_dubbo_methods(self, servername):
global Host
zk = KazooClient(hosts="{}".format(Host))
zk.start()
urls = []
list = zk.get_children("dubbo")
for i in list:
if servername in i:
try:
# 获取服务发布方
gg = zk.get_children("/dubbo/{}/providers".format(i))
if gg:
for j in gg:
url = urllib.parse.unquote(j)
if url.startswith('dubbo:') and url.find("group=" + self.run_env)>=0:
urls.append(url.split('dubbo://')[1])
except Exception as e:
zk.stop()
print(e)
paths=[]
if len(urls)==0:
print(json.dumps({"error":1, "errorMsg":"urls is null"}, indent=4))
zk.stop()
return
for i in urls:
try:
path, temp = i.split('/')
service=temp.split('?')[0]
method=temp.split('methods=')[1].split('&')[0].split(',')
paths.append(path)
except Exception as e:
zk.stop()
print(e)
services = {"service": service, "paths": paths, "method": method}
print(json.dumps(services, indent=4))
zk.stop()
return services
def send_dubbo_msg(self, servhost, servport, interface, method, param):
try:
# 初始化dubbo对象
conn = dubbo_telnet.connect(servhost, servport)
# 设置telnet连接超时时间
conn.set_connect_timeout(5)
# 设置dubbo服务返回响应的编码
conn.set_encoding('gbk')
data=conn.invoke(interface, method, param)
return data
except Exception as e:
print(e)
return e
#zookeeper的地址
env = 'test'
dubbo = dubboHelper(env)
#返回zk中注册的 每个(主机IP + 端口) 下所有的服务名称
#dubbo.get_dubbo_services()
#返回zk中注册的Server所有的服务实例地址和方法名称
dubbo.get_dubbo_methods(serverName)
# send_dubbo_msg('服务提供者ip','服务提供者port','服务名','调用方法','发送数据')
param='{"class":xxx,"appId":xxx,"activityId":xxx,"orderId":"xxx","startTime":xxx,"endTime":xxx}'
res=dubbo.send_dubbo_msg(host, port, serverName, methodName, param)
print(res)