我设法从单体应用程序中查找领事服务器。在 pom.xml 中添加依赖项
<!-- https://mvnrepository.com/artifact/com.orbitz.consul/consul-client -->
<dependency>
<groupId>com.orbitz.consul</groupId>
<artifactId>consul-client</artifactId>
<version>0.17.0</version>
</dependency>
下面的方法将返回主机名、端口,例如http://hostname:port
服务正在运行的端口,以及在 consul 上注册的端口
public String serviceUrl(String serviceName) {
String consulRegistryHost = System.getProperty("consul.registry.url");
Consul consul = Consul.builder().withUrl(consulRegistryHost).build(); // connect to Consul on localhost by default , otherwise
HealthClient healthClient = consul.healthClient();
List<ServiceHealth> nodes = healthClient.getAllServiceInstances(serviceName).getResponse(); // discover only "passing" nodes
if (nodes != null && nodes.size() > 0 ) {
ServiceHealth node = nodes.get(0);
return "http://"+node.getService().getAddress()+":"+node.getService().getPort();
}
return null;
}