获取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;
    }

}

 

posted @ 2021-01-06 15:26  码农的进击  阅读(1569)  评论(0编辑  收藏  举报