获取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, ...
随机推荐
- IDA 创建本地类型
在IDA中我们常常使用 shift+F9打开结构体视图,ins 创建结构体,但操作有些繁琐. 我们可以在View-->Open Subviews-->Local Types(视图--> ...
- 【Azure Developer】Github Action部署资源(ARM模板)到Azure中国区时,遇见登录问题的解决办法
问题描述 在参考文档"使用 GitHub Actions 部署 ARM 模板"一文中,由于是在中国区Azure上操作,所以生产的部署凭证为中国区凭证.当创建工作流时,在登录到Azu ...
- MongoDB中“$”操作符表达式汇总
MongoDB中"$"操作符表达式汇总 查询 比较操作 $eq 语法:{ : { $eq: } } 释义:匹配等于(=)指定值的文档 举例: 查询age = 20的文档: db.p ...
- 单链表c语言实现的形式
包括初始化,创建,查询,长度,删除,清空,销毁等操作 代码如下: #include<stdio.h> #include<stdlib.h> //定义单链表的数据类型 typed ...
- Shell:如何遍历包含空格的文本
Blog:博客园 个人 翻译自Looping Through a File that Contains Spaces – Bash for Loop 处理包含空格或特殊字符的文件是每个使用Linux的 ...
- js 更改json的 key
let t = data.map(item => { return{ fee: item['费用'], companyName1: item.companyName, remark1: item ...
- 什么是 Ansible - 使用 Ansible 进行配置管理
[注]本文译自:https://www.edureka.co/blog/what-is-ansible/ Ansible 是一个开源的 IT 配置管理.部署和编排工具.它旨在为各种自动化挑战提供巨 ...
- Java 获取Word中的标题大纲(目录)
概述 Word中的标题可通过"样式"中的选项来快速设置(如图1), 图1 在添加目录时,可将"有效样式"设置为"目录级别"显示(如图2),一 ...
- Hadoop完整搭建过程(二):伪分布模式
1 伪分布模式 伪分布模式是运行在单个节点以及多个Java进程上的模式.相比起本地模式,需要进行更多配置文件的设置以及ssh.YARN相关设置. 2 Hadoop配置文件 修改Hadoop安装目录下的 ...
- redhat7.6 安装 Python 3
redhat7.6 默认安装了python2.7. 查看已安装python情况 cd / # 定位到根目录 whereis python # 查看python所在目录 /usr/bin cd /usr ...