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


相关推荐
格子先生Lab5 天前
Nacos 详细介绍:微服务架构中的服务发现与配置管理利器
微服务·架构·服务发现
haohulala5 天前
【微服务学习二】nacos服务发现与负载均衡
学习·微服务·服务发现
周周的奇妙编程5 天前
红队视角出发的k8s敏感信息收集——服务发现与 DNS 探测
容器·kubernetes·服务发现
卷心菜不卷Iris6 天前
第1章大型互联网公司的基础架构——1.5 服务发现
微服务·服务发现·注册中心·服务注册·互联网大厂·大厂基础架构
俏布斯10 天前
服务发现(Dubbo-zookeeper)
zookeeper·服务发现·dubbo
企鹅侠客14 天前
k8s服务发现有哪些方式?
容器·kubernetes·服务发现
快乐就好ya15 天前
skywalking服务追踪
java·spring boot·spring cloud·微服务·服务发现
2的n次方_20 天前
Eureka 服务注册和服务发现的使用
spring boot·spring cloud·云原生·eureka·服务发现
Rinai_R1 个月前
【Golang/gRPC/Nacos】在golang中将gRPC和Nacos结合使用
经验分享·笔记·学习·微服务·nacos·golang·服务发现
周杰伦_Jay1 个月前
详细介绍:Kubernetes(K8s)的技术架构(核心概念、调度和资源管理、安全性、持续集成与持续部署、网络和服务发现)
网络·ci/cd·架构·kubernetes·服务发现·ai编程