最近要做一个功能,服务上线下线的操作,于是百度了一下,网上基本是下面这种代码形式。
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
希望对大家有帮助
来源:oschina
链接:https://my.oschina.net/sprouting/blog/4300769