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


相关推荐
九皇叔叔1 天前
【04】微服务系列 之 Nacos 注册中心(服务发现)
java·微服务·nacos·服务发现
jiayong238 天前
Kubernetes 网络与服务发现面试题详解
网络·kubernetes·服务发现
努力也学不会java10 天前
【Spring Cloud】 服务注册/服务发现
人工智能·后端·算法·spring·spring cloud·容器·服务发现
廋到被风吹走10 天前
【配置中心】Nacos 配置中心与服务发现深度解析
开发语言·服务发现·php
MengFly_14 天前
Java广播 —如何利用广播做服务发现
java·网络·服务发现
rchmin18 天前
Nacos服务与配置管理平台介绍
架构·服务发现·配置管理
oMcLin21 天前
如何在 CentOS 7.9 上配置并调优 Docker Swarm 集群,确保跨多个节点的高效服务发现与负载均衡?
docker·centos·服务发现
喵叔哟22 天前
19.服务集成与通信
后端·docker·容器·服务发现
喵叔哟1 个月前
15.故障排查与调试
后端·docker·容器·服务发现
没有bug.的程序员1 个月前
Spring Cloud Gateway 架构与执行流程:从原理到性能优化的深度探索
微服务·云原生·eureka·性能优化·架构·sentinel·服务发现