要想使用 Eureka 的服务发现机制,首先我们需要在客户端的主启动类上加上一个注解 @EnableDiscoveryClient
:
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class, args);
}
}
在控制器中,我们首先要注入 org.springframework.cloud.client.discovery
包下的 DiscoveryClient
实体类:
@Resource
private DiscoveryClient discoveryClient;
然后写一个接口:
代码语言:javascript复制@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.getServiceId() "t" instance.getHost() "t" instance.getPort() "t" instance.getUri());
}
return this.discoveryClient;
}
我们可以通过 discoveryClient
获取到服务的名称以及端口号和 URI 等信息,访问结果如下:
{"services":["cloud-payment-service"],"order":0}