如何发现服务呢?
服务注册到 Eureka 集群中。需要通过 RestTemplate和@LoadBalanced 实现服务发现调用(http) 。
在上一篇笔记中,order 服务 通过 estTemplate和@LoadBalanced 实现调用 payment服务. 是通过注册在 Eureka 集群中的服务名称来调用的。
那么如何发现这些服务呢?也就是说如何知道注册在 Eureka 集群中的服务名称
通过DiscoveryClient 和 @EnableDiscoveryClient 注解实现
<font color="red">正常来讲,服务发现应该是服务调用者的事情。这里为了方便代码写在了PaymentController类里.只是为了实现自测</font>
主启动类
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class PaymentMain8002 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8002.class, args);
}
}
控制器 PaymentController.java
@GetMapping(value = "/payment/discovery")
public Object discovery() {
List<String> services = discoveryClient.getServices();
for (String service : services) {
log.info("===================== service: " + service);
}
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
for (ServiceInstance instance : instances) {
log.info("********************** instance: " + instance.getServiceId()
+ instance.getHost()
+ instance.getPort()
+ instance.getUri());
}
return this.discoveryClient;
}
访问: localhost/payment/discovery
{
"order": 0,
"services": [
"cloud-payment-service",
"cloud-order-service"
]
}
2023-06-20 23:13:57.410 INFO [cloud-payment-service,a84f2b64acc1e87a,a84f2b64acc1e87a,true] 7444 --- [nio-8002-exec-1] c.j.s.controller.PaymentController : ===================== service: cloud-payment-service
2023-06-20 23:13:57.411 INFO [cloud-payment-service,a84f2b64acc1e87a,a84f2b64acc1e87a,true] 7444 --- [nio-8002-exec-1] c.j.s.controller.PaymentController : ===================== service: cloud-order-service
2023-06-20 23:13:57.412 INFO [cloud-payment-service,a84f2b64acc1e87a,a84f2b64acc1e87a,true] 7444 --- [nio-8002-exec-1] c.j.s.controller.PaymentController : ********************** instance: CLOUD-PAYMENT-SERVICE192.168.2.618001http://192.168.2.61:8001
2023-06-20 23:13:57.412 INFO [cloud-payment-service,a84f2b64acc1e87a,a84f2b64acc1e87a,true] 7444 --- [nio-8002-exec-1] c.j.s.controller.PaymentController : ********************** instance: CLOUD-PAYMENT-SERVICE192.168.2.618002http://192.168.2.61:8002
标签:service,Spring,PaymentController,Eureka,instance,cloud,a84f2b64acc1e87a,payment,
From: https://blog.51cto.com/u_15524534/6525988