AdminApiUtil.java 3.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package com.xxl.job.core.util;

import com.xxl.job.core.biz.model.ReturnT;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
X
xueli.xue 已提交
17
import java.util.HashSet;
18
import java.util.List;
X
xueli.xue 已提交
19
import java.util.Set;
20 21 22 23 24 25 26 27 28 29

/**
 * @author xuxueli 2017-05-10 21:28:15
 */
public class AdminApiUtil {
	private static Logger logger = LoggerFactory.getLogger(AdminApiUtil.class);

	public static final String CALLBACK = "/api/callback";
	public static final String REGISTRY = "/api/registry";

X
xueli.xue 已提交
30 31
	private static List<String> adminAddressList = null;
	public static void init(String adminAddresses){
32
		// admin assress list
X
xueli.xue 已提交
33 34 35
		if (adminAddresses != null) {
			Set<String> adminAddressSet = new HashSet<String>();
			for (String adminAddressItem: adminAddresses.split(",")) {
X
xueli.xue 已提交
36
				if (adminAddressItem.trim().length()>0) {
X
xueli.xue 已提交
37
					adminAddressSet.add(adminAddressItem);
38 39
				}
			}
X
xueli.xue 已提交
40
            adminAddressList = new ArrayList<String>(adminAddressSet);
41
		}
X
xueli.xue 已提交
42
	}
X
xueli.xue 已提交
43 44 45 46
	public static boolean allowCallApi(){
        boolean allowCallApi = (adminAddressList!=null && adminAddressList.size()>0);
        return allowCallApi;
    }
X
xueli.xue 已提交
47 48 49

	public static ReturnT<String> callApiFailover(String subUrl, Object requestObj) throws Exception {

X
xueli.xue 已提交
50 51
		if (!allowCallApi()) {
			return new ReturnT<String>(ReturnT.FAIL_CODE, "allowCallApi fail.");
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
		}

		for (String adminAddress: adminAddressList) {
			ReturnT<String> registryResult = null;
			try {
				String apiUrl = adminAddress.concat(subUrl);
				registryResult = callApi(apiUrl, requestObj);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			if (registryResult!=null && registryResult.getCode()==ReturnT.SUCCESS_CODE) {
				return ReturnT.SUCCESS;
			}
		}
		return ReturnT.FAIL;
	}

	public static ReturnT<String> callApi(String finalUrl, Object requestObj) throws Exception {
		HttpPost httpPost = new HttpPost(finalUrl);
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try {

			// timeout
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectionRequestTimeout(10000)
					.setSocketTimeout(10000)
					.setConnectTimeout(10000)
					.build();

			httpPost.setConfig(requestConfig);

			// data
			if (requestObj != null) {
				String json = JacksonUtil.writeValueAsString(requestObj);

				StringEntity entity = new StringEntity(json, "utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");

				httpPost.setEntity(entity);
			}

			// do post
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (null != entity) {
98
				String responseMsg = EntityUtils.toString(entity, "UTF-8");
99 100
				if (response.getStatusLine().getStatusCode() != 200) {
					EntityUtils.consume(entity);
101 102
					return new ReturnT<String>(response.getStatusLine().getStatusCode(),
							"StatusCode(+"+ response.getStatusLine().getStatusCode() +") Error,response:" + responseMsg);
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
				}

				EntityUtils.consume(entity);
				if (responseMsg!=null && responseMsg.startsWith("{")) {
					ReturnT<String> result = JacksonUtil.readValue(responseMsg, ReturnT.class);
					return result;
				}
			}
			return ReturnT.FAIL;
		} catch (Exception e) {
			logger.error("", e);
			return new ReturnT<String>(ReturnT.FAIL_CODE, e.getMessage());
		} finally {
			if (httpPost!=null) {
				httpPost.releaseConnection();
			}
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}