eureka-获取服务列表(各种状态)
在刚开始做的时候也搜了下搜到的大多是下面的第一种方法,这种方法很简单,但并不是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-获取服务列表(各种状态)的更多相关文章
- Eureka获取服务列表源码解析
在之前的文章:EurekaClient自动装配及启动流程解析中,我们提到了在类DiscoveryClient的构造方法中存在一个刷新线程和从服务端拉取注册信息的操作 这两个就是eureka获取服务列表 ...
- Android ExpandableListView使用+获取SIM卡状态信息
ExpandableListView 是一个可以实现下拉列表的控件,大家可能都用过QQ,QQ中的好友列表就是用ExpandableListView实现的,不过它是自定义的适配器.本篇 博客除了要介绍E ...
- android获取系统wifi状态等
WIFI 获取WIFI状态 WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE); ...
- Android编程 获取网络连接状态 及调用网络配置界面
获取网络连接状态 随着3G和Wifi的推广,越来越多的Android应用程序需要调用网络资源,检测网络连接状态也就成为网络应用程序所必备的功能. Android平台提供了ConnectivityMan ...
- Android编程获取网络连接状态及调用网络配置界面
获取网络连接状态 随着3G和Wifi的推广,越来越多的Android应用程序需要调用网络资源,检测网络连接状态也就成为网络应用程序所必备的功能. Android平台提供了ConnectivityMan ...
- js判断获取浏览器关闭状态
如题,js获取浏览器关闭状态,可实现判断选择是否关闭. <html> <head> <title> </title> </head> < ...
- Android获取当前网络状态
Android获取当前网络状态 效果图 有网络 没有网络 源码 下载地址(Android Studio工程):http://download.csdn.net/detail/q4878802/9052 ...
- Android记录3--ExpandableListView使用+获取SIM卡状态信息
Android记录3--ExpandableListView使用+获取SIM卡状态信息 2013年8月9日Android记录 ExpandableListView是一个可以实现下拉列表的控件,大家可能 ...
- UNIX环境编程学习笔记(21)——进程管理之获取进程终止状态的 wait 和 waitpid 函数
lienhua342014-10-12 当一个进程正常或者异常终止时,内核就向其父进程发送 SIGCHLD信号.父进程可以选择忽略该信号,或者提供一个该信号发生时即被调用的函数(信号处理程序).对于这 ...
- SAP中对于获取订单的状态
在SAP中对于如何获取订单的状态,提供了至少两个函数,分别是 STATUS_READ 和 STATUS_TEXT_EDIT.下面简单介绍这两个函数 1.STATUS_READ 改函数的实现原理大 ...
随机推荐
- redis安装并设置开机启动
1.下载并上传redis安装包至linux服务器目录:/usr/local/redis. 2.解压:tar -zxvf redis-5.0.7.tar.gz 3.编译安装:make && ...
- 使用Image Sharp 对二维码图片中间加入logo图片
1.在NuGet包源加入Image Sharp包源 2.在需要用到Image Sharp的项目中安装以下的插件 3.调用图片上绘制图片的方法
- [JSOI2010]快递服务
Description Luogu4046 BZOJ1820 Solution 暴力DP很好想,\(f[i][j][k][l]\)表示处理到第\(i\)个任务,三个人在\(i,j,k\)的方案数.显然 ...
- git中设置代理
说明:在某种原因下,整个网络都是使用代理的情况下,需要使用git clone,这时就需要设置代理了. 在没有设置代理的时候,直接克隆报错 Failed to connect to gitee.com ...
- python使用selenium驱动chromium防止浏览器自动升级失效!
python爬虫或者自动化项目中有时会用到selenium自动化测试框架,驱动chrom时由于谷歌浏览器自动升级,会造成驱动和浏览器版本不匹配问题,这时可以用到Chromium,这是谷歌推出用于开发目 ...
- vue学习指南:第十四篇(详细) - Vue的 路由 第四篇 ( 路由的导航守卫 )
导航守卫 一.全局导航守卫 1. 全局导航守卫,把方法给 router,只要路由发生改变跳转都会触发这个函数 2. 每个路由 都有一个 meta 3. 全局导航守卫分两种: 1. 全局前置导航守卫:路 ...
- 浅析ReDoS
ReDoS(Regular expression Denial of Service) 正则表达式拒绝服务攻击.开发人员使用了正则表达式来对用户输入的数据进行有效性校验, 当编写校验的正则表达式存在缺 ...
- Map中放入对象字符串转义问题
在做Zuul网关日志处理的时候,有以下需求: (1)记录请求成功的日志,要求记录请求返回的结果. 遇到的问题: (1)当请求的结果事对象时,会将其转成字符串,在put进map的时候,字符串就会被转义 ...
- normalization, standardization and regularization
Normalization Normalization refers to rescaling real valued numeric attributes into the range 0 and ...
- SCRIPT429: Automation 服务器不能创建对象
安全模式设置成“中”,如果javascript脚本中报这个错误,应将IE的安全设置“不允许运行未标记为安全的activeX控件”启用即可. 注意如果您将相应的网站设成“受信任的站点”,必须对“受信任的 ...