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


相关推荐
逻极20 小时前
Kubernetes 从入门到精通:云原生容器编排
kubernetes·k8s·服务发现·容器编排
牛奶咖啡136 天前
k8s容器编排技术实践——K8s中服务发现ingress、ingress controller 应用实践
kubernetes·服务发现·ingress·ingress-nginx·部署ingress-nginx·部署ingress的三种方法·ingress的服务发现原理
追寻少年9 天前
Kubernetes 服务发现和域名解析-cnblog
容器·kubernetes·服务发现
念何架构之路14 天前
接入LVS+Nginx和服务发现
nginx·服务发现·lvs
IT策士14 天前
第29篇 k8s之Service 与 Endpoints 深入:服务发现原理
容器·kubernetes·服务发现
tellmewhoisi16 天前
Docker Compose最巧妙的设计之一——内置的服务发现机制
docker·服务发现
我是唐青枫16 天前
C#.NET YARP 服务发现实战:接入 Consul 和 Kubernetes 动态发现后端服务
c#·服务发现·.net
成为你的宁宁18 天前
【Prometheus基于文件的服务发现】
服务发现·prometheus
笨鸟先飞的橘猫20 天前
skynet——服务发现学习
学习·服务发现
AI云原生24 天前
容器网络模型与服务发现:从踩坑到精通,Kubernetes 网络问题排查全指南
服务器·网络·云原生·容器·kubernetes·云计算·服务发现