public class HttpAsyncUtils {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(HttpAsyncUtils.class);
private static CloseableHttpAsyncClient httpAsyncClient = null;
static {
OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
try {
logger.info("===========开始构建http异步连接池================");
ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
PoolingNHttpClientConnectionManager pool = new PoolingNHttpClientConnectionManager(ioReactor);
pool.setMaxTotal(200); //设置最多连接数
pool.setDefaultMaxPerRoute(20); //设置每个host最多20个连接数
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(3000) //设置请求响应超时时间
.setConnectTimeout(3000) //设置请求连接超时时间
.build();
httpAsyncClient = HttpAsyncClients.custom()
.setConnectionManager(pool) //设置连接池
.setDefaultRequestConfig(requestConfig) //设置请求配置
.build();
} catch (IOReactorException e) {
e.printStackTrace();
logger.error("============构建异步连接失败=============", e);
}
httpAsyncClient.start(); //启动异步连接
logger.info("===========http异步连接池创建成功================");
}
public static Future<HttpResponse> post(String url, Object param) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
if (param != null) {
Map<String, Object> map = OBJECT_MAPPER.convertValue(param, Map.class); //通过jackson转换参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() != null) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
paramList.add(pair);
}
}
}
final HttpPost post = new HttpPost(url); //创建POSt请求
HttpEntity entity = new UrlEncodedFormEntity(paramList, Charset.forName("utf-8"));
post.setEntity(entity); //设置请求参数
//发送请求并返回future
return httpAsyncClient.execute(post, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse response) {
System.out.println("执行接口completed:"+post.getRequestLine() + "->" + response.getStatusLine());
}
@Override
public void failed(Exception ex) {
System.out.println("执行接口failed"+post.getRequestLine() + "->" + ex);
}
@Override
public void cancelled() {
System.out.println("执行接口cancelled:"+post.getRequestLine() + " cancelled");
}
});
}
//通过jackson对Future响应格式化
public static <T> T parse(Future<HttpResponse> httpResponseFuture, Class<T> clazz) {
try {
String str = "";
HttpResponse httpResponse = httpResponseFuture.get();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
str = EntityUtils.toString(entity);
}
if (StringUtils.isBlank(str)) {
logger.info("获取执行返回值为空");
return null;
}
logger.info("获取执行返回值={}", str);
return OBJECT_MAPPER.readValue(str.getBytes("utf-8"), clazz);
} catch (IOException e) {
e.printStackTrace();
logger.error("接口IOException异常", e);
} catch (InterruptedException e) {
e.printStackTrace();
logger.error("接口InterruptedException异常", e);
} catch (ExecutionException e) {
e.printStackTrace();
logger.error("接口ExecutionException异常", e);
}
return null;
}
}