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


相关推荐
AI云原生1 天前
容器网络模型与服务发现:从踩坑到精通,Kubernetes 网络问题排查全指南
服务器·网络·云原生·容器·kubernetes·云计算·服务发现
日取其半万世不竭8 天前
Consul:服务发现与健康检查,微服务架构的注册中心
架构·服务发现·consul
Daorigin_com9 天前
道本科技三大系统形成的“合同—合规—法务”智能闭环!
科技·职场和发展·分类·服务发现·边缘计算·集成学习·敏捷流程
布吉岛的石头11 天前
Nacos服务发现与配置中心:微服务注册中心实战
微服务·架构·服务发现
marsh020620 天前
42 openclaw服务发现机制:动态管理微服务实例
ai·服务发现·编程·技术
AOwhisky22 天前
Kubernetes调度与服务暴露:从“定时任务”到“服务发现”的完全指南
linux·运维·云原生·容器·kubernetes·服务发现
白晨并不是很能熬夜22 天前
【RPC】第 4 篇:服务发现 — Zookeeper + 缓存容错
java·后端·程序人生·缓存·zookeeper·rpc·服务发现
运维全栈笔记25 天前
K8S部署WordPress+MySQL:模块化YAML配置详解
服务器·mysql·docker·云原生·容器·kubernetes·服务发现
雨奔1 个月前
Kubernetes DNS 完全指南:服务发现核心机制与实践
java·kubernetes·服务发现
谢谢蟹老板的蟹黄堡1 个月前
MindSpore:ResNet50中药炮制饮片质量判断最佳实践
服务发现