在刚开始做的时候也搜了下搜到的大多是下面的第一种方法,这种方法很简单,但并不是Eureka展示的那个服务列表,他只包括了注册证成功的,或者说eureka中状态为“Up”的实例列表,对于down掉的实例,并不能获取到,之后再看eureka中提供的REST API的时候发现有个接口可以获取到eureka中注册实例的详细信息:

最后采用了请求该接口,解析xml的形式获取实力列表信息

下面是具体的处理方式:

一、通过springcloud的API获取                                                                                                                                                                                                                                                                            服务列表是在eureka的客户端中获取的

(1)在配置文件application.yml设置erueka的信息

eureka:
instance:
prefer-ip-address: true # 注册服务的时候使用服务的ip地址
client:
service-url:
defaultZone: http://localhost:8761/eureka/

(2)Controller

package com.googosoft.instances.controller;

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;
}
}
public Object getList(String targetName) {
List<Map<String, Object>> servicesList = new ArrayList<>();
//获取服务名称
List<String> serviceNames = discoveryClient.getServices();
for (String serviceName : serviceNames) {
//获取服务中的实例列表
List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
for (ServiceInstance serviceInstance : serviceInstances) {
String serviceInstanceStr= JSON.toJSONString(serviceInstance);
if(serviceInstanceStr!=null){
Map<String, Object> serviceInstanceMap = (Map<String, Object>) JSON.parse(serviceInstanceStr);
if(serviceInstanceMap!=null){
Map<String, Object> instanceInfoMap = (Map<String, Object>)JSON.parse(serviceInstanceMap.get("instanceInfo").toString());
String appName = (String)instanceInfoMap.get("appName");
if(targetName == null){
add(servicesList,appName,instanceInfoMap,serviceInstanceMap);
}else if(appName.contains(targetName.trim())){
add(servicesList,appName,instanceInfoMap,serviceInstanceMap);
}
}
}
}
}
Map<String,Object> map=new HashMap<String,Object>();
map.put("code", 0);
map.put("count", servicesList.size());
map.put("data", servicesList);
return map;

(2)访问

二、通过请求eureka的restAPI,解析xml获取

package com.googosoft.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.impl.util.json.JSONArray;
import org.activiti.engine.impl.util.json.JSONException;
import org.activiti.engine.impl.util.json.JSONObject;
import org.activiti.engine.impl.util.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.googosoft.info.ActuatorURL;
import com.googosoft.model.HttpClientResult;
import com.googosoft.model.Instance;
import com.googosoft.until.DateUtil;
import com.googosoft.until.HttpClientUtil; /**
* @author songyan
* @version 2020年1月7日 下午4:33:33
* @desc
*/
@Service
public class AssemblyService { @Autowired
private InstanceService instanceService; @Value("${spring.application.name}")
private String APPNAME;
@Value("${eureka.client.service-url.defaultZone}")
private String EUREKA_DEFAULT_ZONE;
@Value("${monitor.show-self}")
private boolean MONITOR_SHOW_SELF; public Object updateStatus(String appId, String instanceId, String status) {
String url = EUREKA_DEFAULT_ZONE + ActuatorURL.APPS + "/" + appId + "/" + instanceId + "/status?value="
+ status;
instanceService.updateStatus(new Instance(instanceId, status));
return HttpClientUtil.sendPutReq(url);
} public Map<String,Object> getInstanceList(){
List<Map<String,Object>> instanceList = new ArrayList<>();
HttpClientResult clientResult = HttpClientUtil.sendGetRequest(EUREKA_DEFAULT_ZONE+ActuatorURL.APPS);
JSONObject jsonObject = XML.toJSONObject(clientResult.getContent());
JSONObject applications = jsonObject.getJSONObject("applications"); try {
if(applications.get("application") instanceof JSONArray){
JSONArray serviceInstance = applications.getJSONArray("application");
for (int i = 0; i < serviceInstance.length(); i++) {
JSONObject application = (JSONObject) serviceInstance.get(i);
String appName = application.getString("name");
add(application,instanceList,appName);
}
}else{
JSONObject application = applications.getJSONObject("application");
String appName = application.getString("name");
add(application,instanceList,appName);
}
} catch (JSONException e) {
e.printStackTrace();
System.err.println("applications::"+applications);
} Map<String,Object> map=new HashMap<String,Object>();
map.put("code", 0);
map.put("count", instanceList.size());
map.put("data", instanceList);
return map;
} public void setSysInfo(Map<String, Object> map) {
HttpClientResult clientResult = HttpClientUtil.sendGetRequest(EUREKA_DEFAULT_ZONE + ActuatorURL.APPS);
JSONObject jsonObject = XML.toJSONObject(clientResult.getContent());
JSONObject applications = jsonObject.getJSONObject("applications");
try {
if (applications.get("application") instanceof JSONArray) {
JSONArray serviceInstance = applications.getJSONArray("application");
for (int i = 0; i < serviceInstance.length(); i++) {
JSONObject application = (JSONObject) serviceInstance.get(i);
String appName = application.getString("name");
if ((APPNAME.toUpperCase()).equals(appName.toUpperCase())) {
if (application.get("instance") instanceof JSONObject) {
JSONObject instance = (JSONObject) application.get("instance");
Object homePageUrl = instance.get("homePageUrl");
String instanceId = instance.get("instanceId") + "";
map.put("homePageUrl", homePageUrl);
map.put("appName", APPNAME);
map.put("instanceId", instanceId);
} else {
JSONArray instanceArray = application.getJSONArray("instance");
for (int j = 0; j < instanceArray.length(); j++) {
JSONObject instance = (JSONObject) instanceArray.get(j);
Object homePageUrl = instance.get("homePageUrl");
String instanceId = instance.get("instanceId") + "";
map.put("homePageUrl", homePageUrl);
map.put("appName", APPNAME);
map.put("instanceId", instanceId);
}
}
}
}
} else {
JSONObject application = applications.getJSONObject("application");
String appName = application.getString("name");
if (appName.equals(appName.toUpperCase())) {
if (application.get("instance") instanceof JSONObject) {
JSONObject instance = (JSONObject) application.get("instance");
Object homePageUrl = instance.get("homePageUrl");
String instanceId = instance.get("instanceId") + "";
map.put("homePageUrl", homePageUrl);
map.put("appName", APPNAME);
map.put("instanceId", instanceId);
} else {
JSONArray instanceArray = application.getJSONArray("instance");
for (int j = 0; j < instanceArray.length(); j++) {
JSONObject instance = (JSONObject) instanceArray.get(j);
Object homePageUrl = instance.get("homePageUrl");
String instanceId = instance.get("instanceId") + "";
map.put("homePageUrl", homePageUrl);
map.put("appName", APPNAME);
map.put("instanceId", instanceId);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} public void add(JSONObject application,List<Map<String,Object>> instanceList,String appName){
if(application.get("instance") instanceof JSONObject){
Map<String,Object> instance = handle(application.getJSONObject("instance"),appName);
instanceList.add(instance);
}else{
JSONArray instanceArray = application.getJSONArray("instance");
for (int j = 0; j < instanceArray.length(); j++) {
Map<String,Object> instance = handle((JSONObject) instanceArray.get(j),appName);
instanceList.add(instance);
}
}
} public Map<String,Object> getInstanceShowList(String targetName){
List<Map<String,Object>> instanceList = new ArrayList<>();
HttpClientResult clientResult = HttpClientUtil.sendGetRequest(EUREKA_DEFAULT_ZONE+ActuatorURL.APPS);
JSONObject jsonObject = XML.toJSONObject(clientResult.getContent());
JSONObject applications = jsonObject.getJSONObject("applications"); try {
if(applications.get("application") instanceof JSONArray){
JSONArray serviceInstance = applications.getJSONArray("application");
for (int i = 0; i < serviceInstance.length(); i++) {
JSONObject application = (JSONObject) serviceInstance.get(i);
String appName = application.getString("name");
if((targetName == null ||appName.contains(targetName.trim())) ){
if(MONITOR_SHOW_SELF || !appName.equals(this.APPNAME.toUpperCase())){
add(application,instanceList,appName);
}
}
}
}else{
JSONObject application = applications.getJSONObject("application");
String appName = application.getString("name");
if(targetName == null ||appName.contains(targetName.trim())){
add(application,instanceList,appName);
}
}
} catch (JSONException e) {
e.printStackTrace();
} Map<String,Object> map=new HashMap<String,Object>();
map.put("code", 0);
map.put("count", instanceList.size());
map.put("data", instanceList);
return map;
} public Map<String, Object> getInstanceShowList2(String targetName) {
List<Map<String, Object>> instanceList = new ArrayList<>();
HttpClientResult clientResult = HttpClientUtil.sendGetRequest(EUREKA_DEFAULT_ZONE + ActuatorURL.APPS);
JSONObject jsonObject = XML.toJSONObject(clientResult.getContent());
JSONObject applications = jsonObject.getJSONObject("applications"); try {
if (applications.get("application") instanceof JSONArray) {
//多个应用
handleMultlyApplication(applications,targetName,instanceList);
} else {
//单个应用
instanceList = handleSingleApplication(applications,targetName);
}
} catch (JSONException e) {
e.printStackTrace();
System.err.println("applications::" + applications);
} Map<String, Object> map = new HashMap<String, Object>();
map.put("code", 0);
map.put("count", instanceList.size());
map.put("data", instanceList);
return map;
} private void handleMultlyApplication(JSONObject applications,String targetName,List<Map<String, Object>> instanceList) {
JSONArray serviceInstance = applications.getJSONArray("application");
for (int i = 0; i < serviceInstance.length(); i++) {
JSONObject application = (JSONObject) serviceInstance.get(i);
String appName = application.getString("name");
if ((targetName == null || appName.contains(targetName.trim()))) {
if (MONITOR_SHOW_SELF || !appName.equals(this.APPNAME.toUpperCase())) {
instanceList = getInstanceList(application, targetName);
}
}
}
} /**
* 将applications中符合条件的实例添加到实例列表中,并返回列表数据
* 条件:
* @param applications 应用
* @param targetName 系统实例名称
* @param instanceList
*/
private List<Map<String, Object>> handleSingleApplication(JSONObject applications,String targetName) {
List<Map<String, Object>> instanceList = new ArrayList<>();
JSONObject application = applications.getJSONObject("application");
String appName = application.getString("name");
if (targetName == null || appName.contains(targetName.trim())) {
if (MONITOR_SHOW_SELF || !appName.equals(this.APPNAME.toUpperCase())) {
instanceList = getInstanceList(application , appName);
}
}
return instanceList;
} /**
* 将实例由JsonObject类型转换成需要的Map类型
* @param instance 要处理的实例
* @param appName 实例的名称
* @return
*/
private Map<String, Object> JsonobjToMap(JSONObject instance) {
Map<String, Object> instanceMap = new HashMap<>();
JSONObject leaseInfo = instance.getJSONObject("leaseInfo");
String lastUpdatedTimestamp = DateUtil.stampToDate(instance.get("lastUpdatedTimestamp"));
String registrationTimestamp = DateUtil.stampToDate(leaseInfo.get("registrationTimestamp"));
String lastDirtyTimestamp = DateUtil.stampToDate(instance.get("lastDirtyTimestamp"));
String lastRenewalTimestamp = DateUtil.stampToDate(leaseInfo.get("lastRenewalTimestamp"));
Object homePageUrl = instance.get("homePageUrl");
String instanceId = instance.get("instanceId") + "";
instanceMap.put("port", instance.getJSONObject("port").get("content"));
instanceMap.put("host", instance.get("hostName"));
instanceMap.put("status", getStatus(instanceId, instance.get("status") + ""));
instanceMap.put("lastUpdatedTimestamp", lastUpdatedTimestamp);
instanceMap.put("lastDirtyTimestamp", lastDirtyTimestamp);
instanceMap.put("registrationTimestamp", registrationTimestamp);
instanceMap.put("lastRenewalTimestamp", lastRenewalTimestamp);
instanceMap.put("homePageUrl", homePageUrl);
instanceMap.put("instanceId", instanceId);
return instanceMap;
} private Map<String,Object> handle(JSONObject instance, String appName) {
Map<String,Object> instanceMap = new HashMap<>();
JSONObject leaseInfo = instance.getJSONObject("leaseInfo");
String lastUpdatedTimestamp = DateUtil.stampToDate(instance.get("lastUpdatedTimestamp"));
String registrationTimestamp = DateUtil.stampToDate(leaseInfo.get("registrationTimestamp"));
String lastDirtyTimestamp = DateUtil.stampToDate(instance.get("lastDirtyTimestamp"));
String lastRenewalTimestamp = DateUtil.stampToDate(leaseInfo.get("lastRenewalTimestamp"));
Object homePageUrl = instance.get("homePageUrl");
String instanceId = instance.get("instanceId")+""; instanceMap.put("port", instance.getJSONObject("port").get("content"));
instanceMap.put("host", instance.get("hostName"));
instanceMap.put("status", getStatus(instanceId,instance.get("status")+""));
instanceMap.put("lastUpdatedTimestamp", lastUpdatedTimestamp);
instanceMap.put("lastDirtyTimestamp",lastDirtyTimestamp);
instanceMap.put("registrationTimestamp",registrationTimestamp);
instanceMap.put("lastRenewalTimestamp", lastRenewalTimestamp);
instanceMap.put("homePageUrl", homePageUrl);
instanceMap.put("serviceId", appName);
instanceMap.put("instanceId", instanceId);
return instanceMap;
} /**
* 获取实例的状态
* @param instanceId
* @param status
* @return
*/
private String getStatus(String instanceId, String status) {
Instance instance = instanceService.get(instanceId);
if (instance == null || instance.getTargetStatus() == null || "".equals(instance.getTargetStatus())) {
return status;
} else {
if (status.equals(instance.getTargetStatus())) {
instance.setTargetStatus(null);
instanceService.updateStatus(instance);
return status;
} else {
if ("UP".equals(instance.getTargetStatus())) {
return "启动中";
} else {
return "暂停中";
}
}
}
} /**
* 将applications中符合条件的实例添加到实例列表中,并返回列表数据
* @param application
* @param instanceList
* @param targetName
*/
public List<Map<String, Object>> getInstanceList(JSONObject application,String targetName) {
List<Map<String, Object>> instanceList = new ArrayList<>();
String appName = application.getString("name");
if ((targetName == null || appName.contains(targetName.trim()))) {
if (MONITOR_SHOW_SELF || !appName.equals(this.APPNAME.toUpperCase())) {
if (application.get("instance") instanceof JSONObject) {
Map<String, Object> instance = JsonobjToMap(application.getJSONObject("instance"));
instance.put("serviceId", appName);
instanceList.add(instance);
} else {
JSONArray instanceArray = application.getJSONArray("instance");
for (int j = 0; j < instanceArray.length(); j++) {
Map<String, Object> instance = JsonobjToMap((JSONObject) instanceArray.get(j));
instance.put("serviceId", appName);
instanceList.add(instance);
}
}
}
}
return instanceList;
} }

eureka-获取服务列表(各种状态)的更多相关文章

  1. Eureka获取服务列表源码解析

    在之前的文章:EurekaClient自动装配及启动流程解析中,我们提到了在类DiscoveryClient的构造方法中存在一个刷新线程和从服务端拉取注册信息的操作 这两个就是eureka获取服务列表 ...

  2. Android ExpandableListView使用+获取SIM卡状态信息

    ExpandableListView 是一个可以实现下拉列表的控件,大家可能都用过QQ,QQ中的好友列表就是用ExpandableListView实现的,不过它是自定义的适配器.本篇 博客除了要介绍E ...

  3. android获取系统wifi状态等

    WIFI 获取WIFI状态 WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); ...

  4. Android编程 获取网络连接状态 及调用网络配置界面

    获取网络连接状态 随着3G和Wifi的推广,越来越多的Android应用程序需要调用网络资源,检测网络连接状态也就成为网络应用程序所必备的功能. Android平台提供了ConnectivityMan ...

  5. Android编程获取网络连接状态及调用网络配置界面

    获取网络连接状态 随着3G和Wifi的推广,越来越多的Android应用程序需要调用网络资源,检测网络连接状态也就成为网络应用程序所必备的功能. Android平台提供了ConnectivityMan ...

  6. js判断获取浏览器关闭状态

    如题,js获取浏览器关闭状态,可实现判断选择是否关闭. <html> <head> <title> </title> </head> < ...

  7. Android获取当前网络状态

    Android获取当前网络状态 效果图 有网络 没有网络 源码 下载地址(Android Studio工程):http://download.csdn.net/detail/q4878802/9052 ...

  8. Android记录3--ExpandableListView使用+获取SIM卡状态信息

    Android记录3--ExpandableListView使用+获取SIM卡状态信息 2013年8月9日Android记录 ExpandableListView是一个可以实现下拉列表的控件,大家可能 ...

  9. UNIX环境编程学习笔记(21)——进程管理之获取进程终止状态的 wait 和 waitpid 函数

    lienhua342014-10-12 当一个进程正常或者异常终止时,内核就向其父进程发送 SIGCHLD信号.父进程可以选择忽略该信号,或者提供一个该信号发生时即被调用的函数(信号处理程序).对于这 ...

  10. SAP中对于获取订单的状态

    在SAP中对于如何获取订单的状态,提供了至少两个函数,分别是 STATUS_READ 和   STATUS_TEXT_EDIT.下面简单介绍这两个函数 1.STATUS_READ  改函数的实现原理大 ...

随机推荐

  1. Spring-session+Redis解决Session共享

    1. 保证Redis启动           2. 导入依赖                SpringBoot+Spring-Session+Redis <!--spring boot 与re ...

  2. SpringMVC流程图示

  3. JDK8-》 ⽅法引⽤与构造函数引⽤

    以前⽅法调⽤ 对象.⽅法名 或者 类名.⽅法名 jdk1.8提供了另外⼀种调⽤⽅式 ::   说明:⽅法引⽤是⼀种更简洁易懂的lambda表达式,操作符是双冒号::,⽤来直接访问类或者实例 已经存在的 ...

  4. thinkphp3.2 中 Memcache 的配置和使用(memcahe的使用场景)

    Thinkphp的默认缓存方式是以File方式,在/Runtime/Temp 下生成了好多缓存文件. TIPS: TP3.2支持的缓存方式有:数据缓存类型,支持:File|Db|Apc|Memcach ...

  5. c#中的yield词法

    yield关键字的作用是将当前集合中的元素立即返回,实例: 通过断点可以看到,控制台每显示一个集合中的元素,都会到query方法中去取集合元素. 其实yield return是“语法糖”,其本质是生成 ...

  6. Hydra暴力破解工具

    hydra [[[-l LOGIN|-L FILE] [-p PASS|-P FILE]] | [-C FILE]] [-e nsr] [-o FILE] [-t TASKS] [-M FILE [- ...

  7. Python中的模块简单认识

    将自己定义的方法,变量存放在文件中,为一些脚本或者交互式的解释器实例使用,这个文件称为模块. 细说的话,模块可以分为四个通用类别: 1 使用python编写的.py文件(自定义模块) 2 已被编译为共 ...

  8. IntelliJ IDEA 2017.3百度-----树状结构

    ------------恢复内容开始------------ ------------恢复内容结束------------

  9. C++-POJ1017-Packets

    贪心算法,思路见代码 本来想搜索,结果有O(1)的算法,我佛了 其实每一种6x6的方案可以打表预处理,然后dp or search 但是既然可以贪心何乐而不为呢? #include <set&g ...

  10. JS中使用lambda筛选list

    LevelEnum.filter(x=>x.Category=="水利工程")