获取Eureka服务列表的各种场景
一、第一类服务注册到eureka中,获取服务列表
1、基于SpringClientFactory获取服务列表
/**
* <一句话功能简述>
* <功能详细描述>
*
* @author hyf
* @version [版本号, 2019/7/2]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
@RestController
public class DeptController_Consumer { @Resource
private SpringClientFactory factory; @RequestMapping(value = "/getAllServers")
public Object getAllServers(){
//指定服务名
ILoadBalancer lb = factory.getLoadBalancer("MICROSERVICECLOUD");
List<Server> allServers = lb.getAllServers();
List<Server> upServers = lb.getReachableServers();
return allServers;
} }
2、基于DiscoveryClient 获取服务列表
@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;
}
}
二、基于eureka的restAPI,解析xml获取,该方式比较麻烦,但也是最灵活的,只需要知道eureka地址就可以获取,不要注册到eureka中
1、前期准备,解析xml的工具类我使用的是hutool工具包
<dependency>
<groupId>com.xiaoleilu</groupId>
<artifactId>hutool-all</artifactId>
<version>3.0.1</version>
</dependency>
2、需要使用到HttpClientUtils
package com.feihong.springcloud.util; import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Map; import javax.net.ssl.SSLContext; import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils; /**
* <httpClient 工具类> <功能详细描述>
*
* @see [相关类/方法]
* @since [产品/模块版本]
*/ public final class HttpClientUtils { private static LogUtil log = LogUtil.getLogger(HttpClientUtils.class); /**
* 连接池初始化
*/
private static PoolingHttpClientConnectionManager cm = null; /**
* 初始化httpclient 连接池
*/
static {
LayeredConnectionSocketFactory sslsf = null;
try {
sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e) {
log.info(e.getMessage());
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(2);
} private HttpClientUtils() {
} /**
* <配置httpclient> <功能详细描述>
*
* @param timeout 请求超时时间
* @return CloseableHttpClient
* @see [类、类#方法、类#成员]
*/ private static CloseableHttpClient getHttpClient(Integer timeout) {
RequestConfig requestConfig = RequestConfig.custom().
// 设置连接超时时间
setConnectionRequestTimeout(timeout).
// 设置请求超时时间
setConnectTimeout(timeout).
// 设置响应超时时间
setSocketTimeout(timeout).build();
// 超时重试,服务器丢失连接重试
HttpRequestRetryHandlerImpl retry = new HttpRequestRetryHandlerImpl();
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(retry)
.setConnectionManager(cm)
.setConnectionManagerShared(true)
.build();
} /**
* http post <功能详细描述>
*
* @param url 请求的url
* @param timeout 请求响应的时间
* @param param 请求的参数
* @param header 请求头
* @return string
* @see [类、类#方法、类#成员]
*/
private static String httpPost(String url, Integer timeout, Map<String, String> param, Map<String, String> header) {
String msg = "";
// 获取客户端连接对象
CloseableHttpClient httpClient = getHttpClient(timeout); if(StringUtils.isBlank(url)){
throw new RuntimeException("url can not be null");
} HttpPost httpPost = new HttpPost(url);
StringBuilder stringBuilder = new StringBuilder("");
if (null != param) {
for (Map.Entry<String, String> entry : param.entrySet()) {
stringBuilder.append(entry.getKey());
stringBuilder.append('=');
stringBuilder.append(entry.getValue());
stringBuilder.append('&');
}
stringBuilder = stringBuilder.deleteCharAt(stringBuilder.length() - 1);
} CloseableHttpResponse response = null;
try {
StringEntity entityParam = new StringEntity(stringBuilder.toString());
httpPost.setEntity(entityParam);
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
// 执行请求
response = httpClient.execute(httpPost);
// 获得响应的实体对象
HttpEntity entity = response.getEntity();
msg = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) {
log.info("user httpPost request error", e);
} finally {
try {
doClose(httpClient, response);
} catch (IOException e) {
log.error("httpPost close error", e);
}
}
return msg;
} public static String httpGet(String url, Integer timeout, Map<String, String> map, Map<String, String> header) {
String msg = "";
CloseableHttpClient httpClient = getHttpClient(timeout);
CloseableHttpResponse response = null;
try {
// 声明URIBuilder
URIBuilder uriBuilder = new URIBuilder(url); // 判断参数map是否为非空
if (map != null) {
// 遍历参数
for (Map.Entry<String, String> entry : map.entrySet()) {
// 设置参数
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 2 创建httpGet对象,相当于设置url请求地址
HttpGet httpGet = new HttpGet(uriBuilder.build()); // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
response = httpClient.execute(httpGet); // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
// 状态码
// response.getStatusLine().getStatusCode();
// 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
HttpEntity entity = response.getEntity();
msg = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
log.error("user httpGet request error", e);
} finally {
try {
doClose(httpClient, response);
} catch (IOException e) {
log.error("httpGet close error", e);
}
}
// 返回
return msg;
} /**
* 对资源进行关闭
*
* @param httpClient httpClient
* @param response response
*/
private static void doClose(CloseableHttpClient httpClient, CloseableHttpResponse response)
throws IOException {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
package com.feihong.springcloud.util; import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger; /**
* httpclient请求重试策略 httpclient请求重试策略配置类
*
* @see [相关类/方法]
* @since [产品/模块版本]
*/ public class HttpRequestRetryHandlerImpl implements HttpRequestRetryHandler { private LogUtil log = LogUtil.getLogger(HttpRequestRetryHandlerImpl.class); private static final Integer COUNT = 3; /**
* 实现HttpRequestRetryHandler {@inheritDoc}
*/
@Override
public boolean retryRequest(IOException exception, int i, HttpContext httpContext) {
// 重试次数最大为3次
if (i >= COUNT) {
return false;
}
if (exception instanceof NoHttpResponseException) {//没有响应,重试
return true;
} else if (exception instanceof ConnectTimeoutException) {//连接超时,重试
return true;
} else if (exception instanceof SocketTimeoutException) {//连接或读取超时,重试
return true;
} else if (exception instanceof SSLHandshakeException) {//本地证书异常
return false;
} else if (exception instanceof InterruptedIOException) {//被中断
return false;
} else if (exception instanceof UnknownHostException) {//找不到服务器
return false;
} else if (exception instanceof SSLException) {//SSL异常
return false;
} else {
//自己新增log
log.error("HttpRequestRetryHandlerImpl",exception);
return false;
}
} }
3、日志打印工具类
package com.feihong.springcloud.util; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker; /**
* 日志处理工具类
*
* // 方法名|操作人(接口填null)|操作码|操作描述|业务关键信息|异常信息(不需要异常信息就不填)
* logger.error("getMenuFunctionList|{}|{}|角色名称已存在|roleId = {},roleName = {}|exception = {}",
* SessionUtil.getCurrentUserName(), OperateLogConstants.SYS_ROLE_MODIFY, sysRoleVO.getId(),
* sysRoleVO.getRoleName(), CommonUtil.getExceptionMessage(e));
*
* @author llx
*
*/
public final class LogUtil implements Logger { private Logger log; public static LogUtil getLogger(Class<?> clazz) {
return new LogUtil(clazz);
} private LogUtil(Class<?> clazz) {
// 私有构造函数
log = LoggerFactory.getLogger(clazz);
} @Override
public String getName() {
return log.getName();
} @Override
public boolean isTraceEnabled() {
return log.isTraceEnabled();
} @Override
public void trace(String s) {
if (log.isTraceEnabled()) {
log.trace(s);
}
} @Override
public void trace(String s, Object o) {
if (log.isTraceEnabled()) {
log.trace(s, o);
}
} @Override
public void trace(String s, Object o, Object o1) {
if (log.isTraceEnabled()) {
log.trace(s, o, o1);
}
} @Override
public void trace(String s, Object... objects) {
if (log.isTraceEnabled()) {
log.trace(s, objects);
}
} @Override
public void trace(String s, Throwable throwable) {
if (log.isTraceEnabled()) {
log.trace(s, throwable);
}
} @Override
public boolean isTraceEnabled(Marker marker) {
return log.isTraceEnabled(marker);
} @Override
public void trace(Marker marker, String s) {
if (log.isTraceEnabled()) {
log.trace(marker, s);
}
} @Override
public void trace(Marker marker, String s, Object o) {
if (log.isTraceEnabled()) {
log.trace(marker, s, o);
}
} @Override
public void trace(Marker marker, String s, Object o, Object o1) {
if (log.isTraceEnabled()) {
log.trace(marker, s, o, o1);
}
} @Override
public void trace(Marker marker, String s, Object... objects) {
if (log.isTraceEnabled()) {
log.trace(marker, s, objects);
}
} @Override
public void trace(Marker marker, String s, Throwable throwable) {
if (log.isTraceEnabled()) {
log.trace(marker, s, throwable);
}
} @Override
public boolean isDebugEnabled() {
return log.isDebugEnabled();
} @Override
public void debug(String s) {
if (log.isDebugEnabled()) {
log.debug(s);
}
} @Override
public void debug(String s, Object o) {
if (log.isDebugEnabled()) {
log.debug(s, o);
}
} @Override
public void debug(String s, Object o, Object o1) {
if (log.isDebugEnabled()) {
log.debug(s, o, o1);
}
} @Override
public void debug(String s, Object... objects) {
if (log.isDebugEnabled()) {
log.debug(s, objects);
}
} @Override
public void debug(String s, Throwable throwable) {
if (log.isDebugEnabled()) {
log.debug(s, throwable);
}
} @Override
public boolean isDebugEnabled(Marker marker) {
return log.isDebugEnabled(marker);
} @Override
public void debug(Marker marker, String s) {
if (log.isDebugEnabled()) {
log.debug(marker, s);
}
} @Override
public void debug(Marker marker, String s, Object o) {
if (log.isDebugEnabled()) {
log.debug(marker, s, o);
}
} @Override
public void debug(Marker marker, String s, Object o, Object o1) {
if (log.isDebugEnabled()) {
log.debug(marker, s, o, o1);
}
} @Override
public void debug(Marker marker, String s, Object... objects) {
if (log.isDebugEnabled()) {
log.debug(marker, s, objects);
}
} @Override
public void debug(Marker marker, String s, Throwable throwable) {
if (log.isDebugEnabled()) {
log.debug(marker, s, throwable);
}
} @Override
public boolean isInfoEnabled() {
return log.isInfoEnabled();
} @Override
public void info(String s) {
if (log.isInfoEnabled()) {
log.info(s);
}
} @Override
public void info(String s, Object o) {
if (log.isInfoEnabled()) {
log.info(s, o);
}
} @Override
public void info(String s, Object o, Object o1) {
if (log.isInfoEnabled()) {
log.info(s, o, o1);
}
} @Override
public void info(String s, Object... objects) {
if (log.isInfoEnabled()) {
log.info(s, objects);
}
} @Override
public void info(String s, Throwable throwable) {
if (log.isInfoEnabled()) {
log.info(s, throwable);
}
} @Override
public boolean isInfoEnabled(Marker marker) {
return log.isInfoEnabled(marker);
} @Override
public void info(Marker marker, String s) {
if (log.isInfoEnabled()) {
log.info(marker, s);
}
} @Override
public void info(Marker marker, String s, Object o) {
if (log.isInfoEnabled()) {
log.info(marker, s, o);
}
} @Override
public void info(Marker marker, String s, Object o, Object o1) {
if (log.isInfoEnabled()) {
log.info(marker, s, o, o1);
}
} @Override
public void info(Marker marker, String s, Object... objects) {
if (log.isInfoEnabled()) {
log.info(marker, s, objects);
}
} @Override
public void info(Marker marker, String s, Throwable throwable) {
if (log.isInfoEnabled()) {
log.info(marker, s, throwable);
}
} @Override
public boolean isWarnEnabled() {
return log.isWarnEnabled();
} @Override
public void warn(String s) {
if (log.isWarnEnabled()) {
log.warn(s);
}
} @Override
public void warn(String s, Object o) {
if (log.isWarnEnabled()) {
log.warn(s, o);
}
} @Override
public void warn(String s, Object... objects) {
if (log.isWarnEnabled()) {
log.warn(s, objects);
}
} @Override
public void warn(String s, Object o, Object o1) {
if (log.isWarnEnabled()) {
log.warn(s, o, o1);
}
} @Override
public void warn(String s, Throwable throwable) {
if (log.isWarnEnabled()) {
log.warn(s, throwable);
}
} @Override
public boolean isWarnEnabled(Marker marker) {
return log.isWarnEnabled(marker);
} @Override
public void warn(Marker marker, String s) {
if (log.isWarnEnabled()) {
log.warn(marker, s);
}
} @Override
public void warn(Marker marker, String s, Object o) {
if (log.isWarnEnabled()) {
log.warn(marker, s, o);
}
} @Override
public void warn(Marker marker, String s, Object o, Object o1) {
if (log.isWarnEnabled()) {
log.warn(marker, s, o, o1);
}
} @Override
public void warn(Marker marker, String s, Object... objects) {
if (log.isWarnEnabled()) {
log.warn(marker, s, objects);
}
} @Override
public void warn(Marker marker, String s, Throwable throwable) {
if (log.isWarnEnabled()) {
log.warn(marker, s, throwable);
}
} @Override
public boolean isErrorEnabled() {
return log.isErrorEnabled();
} @Override
public void error(String s) {
if (log.isErrorEnabled()) {
log.error(s);
}
} @Override
public void error(String s, Object o) {
if (log.isErrorEnabled()) {
log.error(s, o);
}
} @Override
public void error(String s, Object o, Object o1) {
if (log.isErrorEnabled()) {
log.error(s, o, o1);
}
} @Override
public void error(String s, Object... objects) {
if (log.isErrorEnabled()) {
log.error(s, objects);
}
} @Override
public void error(String s, Throwable throwable) {
if (log.isErrorEnabled()) {
log.error(s, throwable);
}
} @Override
public boolean isErrorEnabled(Marker marker) {
return log.isErrorEnabled(marker);
} @Override
public void error(Marker marker, String s) {
if (log.isErrorEnabled()) {
log.error(marker, s);
}
} @Override
public void error(Marker marker, String s, Object o) {
if (log.isErrorEnabled()) {
log.error(marker, s, o);
}
} @Override
public void error(Marker marker, String s, Object o, Object o1) {
if (log.isErrorEnabled()) {
log.error(marker, s, o, o1);
}
} @Override
public void error(Marker marker, String s, Object... objects) {
if (log.isErrorEnabled()) {
log.error(marker, s, objects);
}
} @Override
public void error(Marker marker, String s, Throwable throwable) {
if (log.isErrorEnabled()) {
log.error(marker, s, throwable);
}
}
}
4、解析XML常量类
package com.feihong.springcloud.util; /**
* <一句话功能简述>
* <功能详细描述>
*
* @author hyf
* @version [版本号, 2021/1/6]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class ParseXmlConstant { private ParseXmlConstant(){} public static final String APPLICATIONS = "applications"; public static final String APPLICATION = "application"; public static final String NAME = "name"; public static final String HOST_NAME = "hostName"; public static final String CONTENT = "content"; public static final String PORT = "port"; public static final String HOME_PAGE_URL = "homePageUrl"; public static final String SERVICE_ID = "serviceId"; public static final String INSTANCE = "instance"; }
5、响应实体类
package com.feihong.springcloud.util; /**
* 返回结果通用对象
*
* @param <T> 结果类型
* @author llx
*/
public class JsonResult<T> {
private int code; private String message; private T data; /**
* 成功返回json结果
*
* @param data 业务对象
* @return json结果
*/
public static <T> JsonResult<T> successResult(T data) {
JsonResult<T> jsonResult = new JsonResult<>();
jsonResult.setCode(ExceptionConstants.PARAM_SUCCESS);
jsonResult.setMessage(
ExceptionConstants.getDefaultMessageMap().get(ExceptionConstants.PARAM_SUCCESS));
jsonResult.setData(data);
return jsonResult;
} /**
* 成功返回json结果
*
* @param data 业务对象
* @return json结果
*/
public static <T> JsonResult<T> successResult(int code, String message, T data) {
JsonResult<T> jsonResult = new JsonResult<>();
jsonResult.setCode(code);
jsonResult.setMessage(message);
jsonResult.setData(data);
return jsonResult;
} /**
* 失败返回json结果
*
* @param code 业务吗
* @param message 返回消息
* @return json结果
*/
public static <T> JsonResult<T> errorResult(int code, String message) {
JsonResult<T> jsonResult = new JsonResult<>();
jsonResult.setCode(code);
jsonResult.setMessage(message);
return jsonResult;
} /**
* 失败返回json结果
*
* @param code 业务异常码,需要通过异常码匹配到异常信息
* @param <T>
* @return
*/
public static <T> JsonResult<T> errorResult(int code) {
JsonResult<T> jsonResult = new JsonResult<>();
jsonResult.setCode(code);
jsonResult.setMessage(ExceptionConstants.getMessage(code));
return jsonResult;
} /**
* 失败返回json结果
*
* @param code 业务吗
* @param message 返回消息
* @param data 响应的业务数据
* @return json结果
*/
public static <T> JsonResult<T> errorResult(int code, String message, T data) {
JsonResult<T> jsonResult = new JsonResult<>();
jsonResult.setCode(code);
jsonResult.setMessage(message);
jsonResult.setData(data);
return jsonResult;
} public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public T getData() {
return data;
} public void setData(T data) {
this.data = data;
} @Override
public String toString() {
return "JsonResult{"
+ "code=" + code
+ ", message='" + message + '\''
+ ", data=" + data + '}';
}
}
package com.feihong.springcloud.controller.vo; /**
* <一句话功能简述>
* <功能详细描述>
*
* @author hyf
* @version [版本号, 2021/1/6]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class EurekaServiceListVo { private String serviceId; private String host; private String homePageUrl; private Integer port; public String getServiceId() {
return serviceId;
} public void setServiceId(String serviceId) {
this.serviceId = serviceId;
} public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public String getHomePageUrl() {
return homePageUrl;
} public void setHomePageUrl(String homePageUrl) {
this.homePageUrl = homePageUrl;
} public Integer getPort() {
return port;
} public void setPort(Integer port) {
this.port = port;
}
}
6、核心代码类
package com.feihong.springcloud.service; import com.feihong.springcloud.controller.vo.EurekaServiceListVo;
import com.feihong.springcloud.util.HttpClientUtils;
import com.feihong.springcloud.util.JsonResult;
import com.feihong.springcloud.util.LogUtil;
import com.feihong.springcloud.util.ParseXmlConstant;
import com.xiaoleilu.hutool.json.JSONArray;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.XML;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; /**
* <一句话功能简述>
* <功能详细描述>
*
* @author hyf
* @version [版本号, 2021/1/6]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
@Service
public class EurekaServiceList { private static LogUtil log = LogUtil.getLogger(EurekaServiceList.class); public JsonResult<List<EurekaServiceListVo>> getInstanceList(String url, String instanceName) { log.info("获取eureka服务列表数据开始|入参:{}", url);
String clientResult = HttpClientUtils.httpGet(url, 10, null, null);
log.info("获取eureka服务列表数据结束|出参:{}", clientResult);
List<EurekaServiceListVo> serviceListVoList = Collections.emptyList();
if (StringUtils.isEmpty(instanceName)) {
serviceListVoList = parseResponseResult(clientResult);
} else {
serviceListVoList = parseResponseResult(clientResult, instanceName);
} return JsonResult.successResult(serviceListVoList);
} private List<EurekaServiceListVo> parseResponseResult(String responseResult, String instanceName) {
JSONObject jsonObject = XML.toJSONObject(responseResult);
if (StringUtils.isEmpty(responseResult)) {
return Collections.emptyList();
}
JSONObject applications = jsonObject.getJSONObject(ParseXmlConstant.APPLICATIONS);
List<EurekaServiceListVo> instanceList = new ArrayList<>(); if (applications.get(ParseXmlConstant.APPLICATION) instanceof JSONArray) {
//多个应用
handleMultiApplication(applications, instanceName, instanceList);
} else {
//单个应用
instanceList = handleSingleApplication(applications, instanceName);
}
return instanceList;
} private void handleMultiApplication(JSONObject applications, String targetName,
List<EurekaServiceListVo> instanceList) {
JSONArray serviceInstance = applications.getJSONArray(ParseXmlConstant.APPLICATION);
for (Object o : serviceInstance) {
JSONObject application = (JSONObject) o;
String appName = application.getStr(ParseXmlConstant.NAME);
if (StringUtils.isEmpty(appName) || !targetName.trim().equals(appName.trim())) {
continue;
}
add(application, instanceList, targetName);
}
} private List<EurekaServiceListVo> handleSingleApplication(JSONObject applications, String targetName) {
List<EurekaServiceListVo> instanceList = new ArrayList<>();
JSONObject application = applications.getJSONObject("application");
String appName = application.getStr(ParseXmlConstant.NAME);
if (StringUtils.isEmpty(appName) || !targetName.trim().equals(appName.trim())) {
return Collections.emptyList();
}
add(application, instanceList, targetName);
return instanceList;
} private List<EurekaServiceListVo> parseResponseResult(String responseResult) {
JSONObject jsonObject = XML.toJSONObject(responseResult);
if (StringUtils.isEmpty(responseResult)) {
return Collections.emptyList();
}
List<EurekaServiceListVo> instanceList = new ArrayList<>();
JSONObject applications = jsonObject.getJSONObject(ParseXmlConstant.APPLICATIONS); if (applications.get(ParseXmlConstant.APPLICATION) instanceof JSONArray) {
JSONArray serviceInstance = applications.getJSONArray(ParseXmlConstant.APPLICATION);
for (Object o : serviceInstance) {
JSONObject application = (JSONObject) o;
String appName = application.getStr(ParseXmlConstant.NAME);
add(application, instanceList, appName);
}
} else {
JSONObject application = applications.getJSONObject(ParseXmlConstant.APPLICATION);
String appName = application.getStr(ParseXmlConstant.NAME);
add(application, instanceList, appName);
}
return instanceList;
} private void add(JSONObject application, List<EurekaServiceListVo> instanceList, String appName) {
if (application.get(ParseXmlConstant.INSTANCE) instanceof JSONObject) {
EurekaServiceListVo serviceListVo = handle(application.getJSONObject(ParseXmlConstant.INSTANCE), appName);
instanceList.add(serviceListVo);
} else {
JSONArray instanceArray = application.getJSONArray(ParseXmlConstant.INSTANCE);
for (Object o : instanceArray) {
EurekaServiceListVo serviceListVo = handle((JSONObject) o, appName);
instanceList.add(serviceListVo);
}
}
} private EurekaServiceListVo handle(JSONObject instance, String appName) {
EurekaServiceListVo serviceListVo = new EurekaServiceListVo();
serviceListVo.setPort(instance.getJSONObject(ParseXmlConstant.PORT).getInt(ParseXmlConstant.CONTENT));
serviceListVo.setHomePageUrl(instance.getStr(ParseXmlConstant.HOME_PAGE_URL));
serviceListVo.setHost(instance.getStr(ParseXmlConstant.HOST_NAME));
serviceListVo.setServiceId(appName);
return serviceListVo;
} }
获取Eureka服务列表的各种场景的更多相关文章
- 使用 http 请求方式获取 eureka server的服务信息
对于一些系统不能接入 eureka server,又需要访问接入eureka server 的服务. 方法一:直接调用服务的地址是一种实现方式,弊端就是地址是写死的,万一服务地址变更则访问不到. 方法 ...
- 微信小程序获取用户信息“授权失败”场景的处理
很多的时候我们在处理小程序功能的时候需要用户获取用户信息,但是呢为了信息安全,用户不授权导致授权失败场景:但是小程序第二次不在启动授权信息弹层,为了用户体验,可以用以下方式处理: function i ...
- 通过LoadBalancerClient获取所有服务列表的IP
说明:LoadBalanced采用轮训的方式请求服务提供者,但是如果针对某些业务需要精确到某个服务提供者或者遍历所有的服务提供者,那么可以通过LoadBalancerClient去获得. 参考: ht ...
- 深入理解Eureka - Eureka Client获取注册信息机制
深入理解Eureka - Eureka Client获取注册信息机 Eureka Client提供了定时获取注册信息的机制.Eureka Client获取注册信息的所有逻辑都在DiscoveryCli ...
- SpringCloud入门1-服务注册与发现(Eureka)
前言 Oracle转让Java,各种动态语言的曝光率上升,Java工程师的未来在哪里?我觉得Spring Cloud让未来有无限可能.拖了半年之久的Spring Cloud学习就从今天开始了.中文教材 ...
- SpringCloud学习1-服务注册与发现(Eureka)
由于样式兼容性问题,本文后半部分被截断,可到个人博客找到本文: https://blog.rmiao.top/springcloud-eureka/ 前言 Oracle转让Java,各种动态语言的曝光 ...
- 跟我学SpringCloud | 第二篇:注册中心Eureka
Eureka是Netflix开源的一款提供服务注册和发现的产品,它提供了完整的Service Registry和Service Discovery实现.也是springcloud体系中最重要最核心的组 ...
- 服务注册组件——Eureka高可用集群搭建
服务注册组件--Eureka高可用集群搭建 什么是Eureka? 服务注册组件:将微服务注册到Eureka中. 为什么需要服务注册? 微服务开发重点在一个"微"字,大型应用拆分成微 ...
- SpringCloud(二)- 服务注册与发现Eureka
离上一篇微服务的基本概念已经过去了几个月,在写那篇博客之前,自己还并未真正的使用微服务架构,很多理解还存在概念上.后面换了公司,新公司既用了SpringCloud也用了Dubbo+Zookeeper, ...
随机推荐
- 【hacker101 CTF】Photo Gallery
0x01 打开首页看到 查看源代码,发现图片都是通过"fetch?id=1"这种方式加载的 简单测了一下存在SQL注入. 直接上sqlmap跑 第一个flag: ^FLAG^d45 ...
- Android Studio中批量注释 Java代码
•ctrl+/ 选中需要注释的多行代码,然后按 ctrl + / 实现多行快速注释: 再次按下 ctrl + / 取消注释. •ctrl+shift+/ 选中一行或几行代码,按 ctrl + shif ...
- jQuery核心函数和静态方法
jQuery核心函数 从jQuery文档中可以看出,jQuery核心函数一共3大类4小类 jQuery(callback) 当DOM加载完成后执行传入的回调函数 <script> $(fu ...
- 使用SignalR ASP.NET Core来简单实现一个后台实时推送数据给Echarts展示图表的功能
什么是 SignalR ASP.NET Core ASP.NET Core SignalR 是一种开放源代码库,可简化将实时 web 功能添加到应用程序的功能. 实时 web 功能使服务器端代码可以立 ...
- python基础(十二):if分支表达式
有时候,我们需要依照某种条件,再决定要不要做某个操作.在Python中,if语句能够帮助我们检查程序的当前状态,告诉计算机接下来该做什么. 条件表达式 每个if后面都跟着一个True或False的表达 ...
- go中控制goroutine数量
控制goroutine数量 前言 控制goroutine的数量 通过channel+sync 使用semaphore 线程池 几个开源的线程池的设计 fasthttp中的协程池实现 Start Sto ...
- 死磕Spring之AOP篇 - 初识JDK、CGLIB两种动态代理
该系列文章是本人在学习 Spring 的过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring 源码分析 GitHub 地址 进行阅读. Spring 版本:5.1 ...
- springcloud面试题【第一期】
全文目录 1:谈一谈你对微服务的理解? 2:微服务之间是如何独立进行通讯的? 3:springcloud和dubbo有哪些区别? 4:springboot和spring cloud得区别? 5:Eur ...
- JavaScript深入理解-PWA渐进式应用
WPA-渐进式 web 应用 PWA 是什么 渐进式 Web 应用,提升 web app 浏览体验. manifest 应用程序清单 基本介绍: web app manifest是 PWA 技术集合中 ...
- 在Android、iOS、Web多平台使用AppGallery Connect性能管理服务
性能管理(App Performance Management,简称APM)是华为应用市场AppGallery Connect(简称AGC)质量系列服务中的其中一项,可以提供分钟级应用性能监控能力,支 ...