服务发现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、 测试访问接口,控制台查看输出


相关推荐
漫步者TZ13 天前
【Nacos系列】服务发现:一致性实现
nacos·服务发现
大数据张老师13 天前
服务发现与动态负载均衡的结合
运维·服务发现·负载均衡
workflower14 天前
敏捷开发项目的需求管理
服务发现·软件工程·需求分析·软件需求·敏捷流程
音元系统14 天前
项目开发中途遇到困难的解决方案
后端·目标跟踪·中间件·服务发现
技术管理修行17 天前
【二】主流架构模式深度对比:单体、前后端分离与微服务
微服务·云原生·架构·服务发现·前后端分离·单体架构
workflower1 个月前
量子比特实现方式
数据仓库·服务发现·需求分析·量子计算·软件需求
workflower1 个月前
金融欺诈有哪些检测手段
服务发现·软件工程·需求分析·软件需求
luckywuxn1 个月前
Eureka实战:怎么配置优化以减少服务发现延迟
云原生·eureka·服务发现
向哆哆1 个月前
Java 微服务架构设计:服务拆分与服务发现的策略
java·微服务·服务发现
xujinwei_gingko1 个月前
服务发现Nacos
java·服务发现