我有一个monolith应用程序A,它需要通过服务发现来调用微服务B. Consul是使用的服务发现服务器。微服务B在Consul服务器上注册。
从A我可以通过给http://hostname:portname/endpoint
调用B.
如何通过服务发现来做到这一点。
我尝试在Monolith Application A中添加依赖项spring-cloud-dependencies
,以便我可以使用org.springframework.cloud.client.discovery.DiscoveryClient
来进行服务发现,但是这个Spring依赖项引入了嵌入式tomcat jar,它与我的jboss冲突,因为它们都运行在8080
的默认端口上。将monolith A转换为springboot应用只是为了服务发现不是一个选择。
是否有非spring选项可以从monolith应用程序到Consul服务器进行服务发现?
我设法从monolith应用程序中查找consul服务器。在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;
}
您可以使用Consul感知负载均衡器(如https://traefik.io/或https://github.com/fabiolb/fabio)或客户端负载均衡解决方案(如https://linkerd.io/)