服务发现Discovery

对于注册进eureka里面的微服务,可以通过服务发现来获得该服务的信息

1、 修改cloud-provider-payment8001的controller

java 复制代码
import com.my.springcloud.utils.RestResponse;
import com.my.springcloud.entities.Payment;
import com.my.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * Discovery服务发现
     */
    @GetMapping(value = "/payment/discovery")
    public Object discovery() {

        // 第一种方式:获取所有服务
        List<String> services = discoveryClient.getServices();
        // 遍历每一个服务
        for (String element : services) {
            log.info("*****element: " + element);
        }
        // 第二种方式:获取键名下的所有服务
        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;
    }
  }

2、 主启动类上加上@EnableDiscoveryClient注解

java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient   //Eureka客户端
@EnableDiscoveryClient //启动服务发现
public class PaymentMain8001 {

    public static void main(String[] args) {
        SpringApplication.run(PaymentMain8001.class, args);
    }
}

3、 测试访问接口,控制台查看输出


相关推荐
喵叔哟15 小时前
10.消息队列集成
后端·服务发现
拾忆,想起18 小时前
设计模式:软件开发的可复用武功秘籍
开发语言·python·算法·微服务·设计模式·性能优化·服务发现
香气袭人知骤暖2 天前
Nacos 服务发现保证机制解析
java·spring·服务发现
拾忆,想起6 天前
Dubbo服务调用幂等性深度解析:彻底解决重复请求的终极方案
微服务·性能优化·服务发现·dubbo
Java天梯之路10 天前
Java SPI:服务发现的轻量级标准
java·面试·服务发现
周杰伦_Jay10 天前
【Nacos指南】服务发现+配置管理从入门到实战
网络·架构·开源·云计算·服务发现
kong790692814 天前
Spring Cloud Consul
spring cloud·服务发现·consul·服务治理
阿拉斯攀登15 天前
SpringCloudAlibaba之Nacos
微服务·服务发现·springcloud
拾忆,想起17 天前
Dubbo动态服务发现配置指南:从基础到云原生实践
服务器·网络·微服务·云原生·架构·服务发现·dubbo
摇滚侠19 天前
2025最新 SpringCloud 教程,Nacos-注册中心-服务发现功能,笔记07
笔记·spring cloud·服务发现