服务发现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 天前
从实验室到量产:测试狗新材料中试的技术路径与平台支撑
测试工具·服务发现·材料工程
八角Z1 天前
AI Agent作为经济参与者的兴起:机器经济与传统金融体系的并存与交织
大数据·人工智能·服务发现
Anita-lee6 天前
泛娱乐出海 APP 运营研究:用户量下滑成因与多语种客服数据化运营解决方案
大数据·产品运营·服务发现·娱乐
钟爱蛋炒饭9 天前
VM虚拟机网络踩坑
服务发现·信息与通信
2401_834636999 天前
K8s 控制器全解:Deployment/DaemonSet/Job/CronJob+Service 服务发现实战宝典
容器·kubernetes·服务发现
TongSearch17 天前
使用 TongZK 做服务注册与服务发现
zookeeper·服务发现·国产化·东方通·tongzk
执笔论英雄19 天前
【大模型推理】sglang PD 分离 : 6473 服务发现
服务发现·sglang
布吉岛的石头25 天前
Java 程序员第 45 阶段11:网关统一路由大模型接口,配合 Nacos 配置治理,灰度路由:基于Nacos元数据实现大模型服务灰度发布与权重路由
java·服务发现
雪碧聊技术1 个月前
Spring Boot项目如何彻底禁用Nacos(服务发现+配置中心),本地启动不再依赖Nacos
spring boot·nacos·服务发现
逻极2 个月前
Kubernetes 从入门到精通:云原生容器编排
kubernetes·k8s·服务发现·容器编排