在刚开始做的时候也搜了下搜到的大多是下面的第一种方法,这种方法很简单,但并不是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. 题解【洛谷P2679】[NOIP2015]子串

    题面 看到求方案数,还要对 \(1000000007\ (1e9+7)\) 取模,一般这样的问题都要考虑 动态规划. 我们设 \(dp_{i,j,k,0/1}\) 表示 \(A_{1\dots i}\ ...

  2. java自动化测试-json返回值校验

    参考: https://blog.csdn.net/xkhgnc_6666/article/details/50250283 实现举例:

  3. shell循环结构解析:for/while/case

    1.for循环结构 for var in item1 item2 ... itemN do command1 command2 ... commandN done 例如,顺序输出当前列表中的数字: # ...

  4. 5.Dockerfile 定制镜像

    概述 Dockerfile 是一个文本文件,其内包含了一条条的 指令(Instruction),每一条指令构建一层,因此每一条指令的内容,就是描述该层应当如何构建. 以之前的 Nginx 镜像为例,这 ...

  5. Wannafly Camp 2020 Day 2A 托米的字符串

    #include <bits/stdc++.h> using namespace std; const int N = 1000005; int n; char str[N]; int a ...

  6. yii2表单提交CSRF验证

    Yii2表单提交默认需要验证CSRF,如果CSRF验证不通过,则表单提交失败,解决方法如下: 第一种解决办法是关闭Csrf public $enableCsrfValidation = false; ...

  7. C语言移除链表元素

    删除链表中等于给定值 val 的所有节点. 示例: 输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4 ...

  8. 164.扩展User模型-继承AbstractUser

    继承自AbstractUser: 如果Abstractuser中定义的字段不能够满足你的项目的要求,并且不想要修改原来User对象上的一些字段,只是想要增加一些字段,那么这时候可以直接继承自djang ...

  9. android 代码实现模拟用户点击、滑动等操作

    /** * 模拟用户点击 * * @param view 要触发操作的view * @param x 相对于要操作view的左上角x轴偏移量 * @param y 相对于要操作view的左上角y轴偏移 ...

  10. unity中添加音量控制的一些步骤

    1.先确认要控制的音源(Audio Source)所使用的输出(Output),例如我这里BGM使用的是MainMixer: 2.暴露音量(Volume)参数,让脚本可以控制.这里如果不暴露出来,脚本 ...