eureka-获取服务列表(各种状态)
阅读原文时间:2023年07月10日阅读:2

在刚开始做的时候也搜了下搜到的大多是下面的第一种方法,这种方法很简单,但并不是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> servicesList = new ArrayList<>();
//获取服务名称
List serviceNames = discoveryClient.getServices();
for (String serviceName : serviceNames) {
//获取服务中的实例列表
List serviceInstances = discoveryClient.getInstances(serviceName);
for (ServiceInstance serviceInstance : serviceInstances) {
String serviceInstanceStr= JSON.toJSONString(serviceInstance);
if(serviceInstanceStr!=null){
Map serviceInstanceMap = (Map) JSON.parse(serviceInstanceStr);
if(serviceInstanceMap!=null){
Map instanceInfoMap = (Map)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 map=new HashMap();
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;  
}

}