5

我正在使用consul在我的环境中发现服务。Consul 的 DNS 服务运行在非标准的 DNS 端口上。我目前的解决方案更多的是解决方法,我想找到更pythonic的方法来做到这一点:

digcmd='dig @127.0.0.1 -p 8600 chef.service.consul +short' # lookup the local chef server via consul
proc=subprocess.Popen(shlex.split(digcmd),stdout=subprocess.PIPE)
out, err=proc.communicate()
chef_server = "https://"+out.strip('\n')
4

2 回答 2

8

您可以使用dnspython库使用 python 进行查询。

from dns import resolver

consul_resolver = resolver.Resolver()
consul_resolver.port = 8600
consul_resolver.nameservers = ["127.0.0.1"]

answer = consul_resolver.query("chef.service.consul", 'A')
for answer_ip in answer:
    print(answer_ip)

使用 dnspython 之类的库比在子进程中调用 dig 更健壮,因为创建进程具有内存和性能影响。

于 2014-09-09T08:07:25.733 回答
2

调用 HTTP API 也很容易urllib.request

import urllib.request

answer = urllib.request.urlopen("http://localhost:8500/v1/catalog/service/chef").read()

服务指南中记录了 HTTP API 的基础知识。

于 2014-10-14T18:26:10.327 回答