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


相关推荐
cccyi72 天前
【C++ 脚手架】etcd 的介绍与使用
c++·服务发现·etcd·服务注册
zs宝来了3 天前
Consul 服务网格原理:Gossip 协议与 Raft 一致性
服务发现·consul·服务网格·gossip协议·raft一致性
zs宝来了3 天前
Nacos 服务发现与配置中心原理:AP 架构与 Distro 协议
nacos·服务发现·配置中心·ap架构·distro协议
@atweiwei8 天前
深入解析gRPC服务发现机制
微服务·云原生·rpc·go·服务发现·consul
ALex_zry8 天前
微服务架构下的服务发现与注册:gRPC服务治理实战
微服务·架构·服务发现
**蓝桉**21 天前
Prometheus的服务发现机制
服务发现·prometheus
Amour恋空22 天前
Nacos服务发现与配置
java·后端·服务发现
qingwufeiyang_5301 个月前
Nacos学习笔记
java·笔记·学习·spring cloud·服务发现
八角Z1 个月前
AI短视频创作实战心得:从玩具到生产力工具亲测
人工智能·机器学习·服务发现·音视频
八角Z1 个月前
AI价值跃迁的核心:输出责任转移与新兴工种的精准重塑
大数据·人工智能·科技·机器学习·计算机视觉·服务发现