HttpClient异步,及连接池应用

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

}




转载于:https://my.oschina.net/UpBoy/blog/669667

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值