微服务 – Spring Cloud – Eureka – Discovery 服务发现

如何发现服务呢?

服务注册到 Eureka 集群中。需要通过 RestTemplate和@LoadBalanced 实现服务发现调用(http) 。

在上一篇笔记中,order 服务 通过 estTemplate和@LoadBalanced 实现调用 payment服务. 是通过注册在 Eureka 集群中的服务名称来调用的。

那么如何发现这些服务呢?也就是说如何知道注册在 Eureka 集群中的服务名称

通过DiscoveryClient 和 @EnableDiscoveryClient 注解实现

正常来讲,服务发现应该是服务调用者的事情。这里为了方便代码写在了PaymentController类里.只是为了实现自测

主启动类

@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

太阳上的雨天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值