eurek获取服务列表为空,非DiscoveryClient.getServices 的方式获取

怎甘沉沦 提交于 2020-08-19 16:42:11

最近要做一个功能,服务上线下线的操作,于是百度了一下,网上基本是下面这种代码形式。

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    private DiscoveryClient discoveryClient;
    
    @RequestMapping("getServicesList")
    @ResponseBody
    public Object getServicesList() {
        List<List<ServiceInstance>> servicesList = new ArrayList<>();
        //获取服务名称
        List<String> serviceNames = discoveryClient.getServices();
        for (String serviceName : serviceNames) {
            //获取服务中的实例列表
            List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
            servicesList.add(serviceInstances);
        }
        return servicesList;
    }
}

实际使用的时候,发现获取不到当前的服务信息,直接找源码,发现这样获取即可。

/**
 * 获取注册中心实例
 * @return
 */
@PostMapping("/getEurekaService")
@ResponseBody
public ResultJson getEurekaService(){
    List<Application> sortedApplications = EurekaServerContextHolder.getInstance().getServerContext().getRegistry().getSortedApplications();
    List<Map> list = new ArrayList<>();
    for (Application application : sortedApplications){
        String name = application.getName();
        List<InstanceInfo> instances = application.getInstances();
        for (InstanceInfo instanceInfo : instances){
            Map<String, Object> map = new HashMap<>();
            //服务名
            map.put("name", name);
            //服务状态
            map.put("status", instanceInfo.getStatus());
            map.put("ip", instanceInfo.getIPAddr());
            map.put("port", instanceInfo.getPort());
            //实例ID
            map.put("instanceId", instanceInfo.getInstanceId());
            //基础请求地址
            map.put("url", instanceInfo.getHomePageUrl());

            list.add(map);
        }
    }

    return new ResultJson("查询成功", list);
}

EurekaServerContextHolder.getInstance().getServerContext().getRegistry().getSortedApplications(); 这个代码就是关键核心代码。

我使用的springcloud版本是

Finchley.RELEASE

希望对大家有帮助

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!