HttpClient工具类-基于4.3.x版本

主要涉及连接池,请求重试相关配置 

package com.epoch.webservices.util;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.protocol.HttpClientContext;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class HttpClientUtil {

    private static final int retryInterval = 3000;

    @Value("${fssc.webservices.interface.voucher-after-push-connection-timeout:10000}")
    public Integer DEFAULT_CONNECTION_TIME_OUT;

    @Value("${fssc.webservices.interface.voucher-after-push-read-timeout:60000}")
    public Integer DEFAULT_READ_TIME_OUT;

    private static CloseableHttpClient httpClient = null;
    private final static Object syncLock = new Object();

    public  CloseableHttpClient getHttpClient(String url) {
        String hostname = url.split("/")[2];
        int port = 80;
        if (hostname.contains(":")) {
            String[] arr = hostname.split(":");
            hostname = arr[0];
            port = Integer.parseInt(arr[1]);
        }
        if (httpClient == null) {
            synchronized (syncLock) {
                if (httpClient == null) {
                    httpClient = createHttpClient(512, 32, 64, hostname, port);
                }
            }
        }
        return httpClient;
    }
 
    public  CloseableHttpClient createHttpClient(int maxTotal,int maxPerRoute, int maxRoute, String hostname, int port) {

        log.info("初始化HttpClient:{}",hostname);

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // 设置最大连接数
        cm.setMaxTotal(maxTotal);
        // 将每个路由默认最大连接数
        cm.setDefaultMaxPerRoute(maxPerRoute);
        HttpHost httpHost = new HttpHost(hostname, port);
        // 设置目标主机对应的路由的最大连接数,会覆盖setDefaultMaxPerRoute设置的默认值
        cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);
 
        // 请求重试处理
        HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> {
            if (executionCount >= 3) {// 如果已经重试了3次,就放弃
                return false;
            }
            log.info("开始第{}重试",executionCount);
            if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
                doRetryInterval();
                return true;
            }
            if (exception instanceof InterruptedIOException) {// 超时
                doRetryInterval();
                return true;
            }
            if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                return false;
            }
            if (exception instanceof UnknownHostException) {// 目标服务器不可达
                return false;
            }
            if (exception instanceof SSLException) {// SSL握手异常
                return false;
            }

            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            // 如果请求是幂等的,就再次尝试
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                doRetryInterval();
                return true;
            }
            return false;
        };
        // 配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIME_OUT)
                .setConnectTimeout(DEFAULT_CONNECTION_TIME_OUT).setSocketTimeout(DEFAULT_READ_TIME_OUT)
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .setConnectionManagerShared(true)
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                .setRetryHandler(httpRequestRetryHandler)
                .setDefaultRequestConfig(requestConfig)
                .build();
        // 开启过期检测线程
        IdleConnectionMonitorThread idleConnectionMonitor = new IdleConnectionMonitorThread(cm);
        idleConnectionMonitor.start();

        return httpClient;
    }

    private  void doRetryInterval() {
        try {
            Thread.sleep(retryInterval);
        } catch (InterruptedException e) {
            log.error("doRetryInterval error",e);
        }
    }

    private  void setPostParams(HttpPost httPost,Map<String, Object> params) {
        List<NameValuePair> nvps = new ArrayList<>();
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        httPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
    }
 
    public  String post(String url, Map<String, Object> params) throws IOException {
        HttpPost httppost = new HttpPost(url);
        setPostParams(httppost, params);
        try (CloseableHttpResponse response = getHttpClient(url).execute(httppost,HttpClientContext.create())){
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            EntityUtils.consume(entity);
            return result;
        }
    }

    public  String post(String url, Map<String, String> headerMap,String jsonBody) throws IOException {
        HttpPost httppost = new HttpPost(url);
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            httppost.setHeader(entry.getKey(),entry.getValue());
        }
        httppost.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));
        try (CloseableHttpResponse response = getHttpClient(url).execute(httppost,HttpClientContext.create())){
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            EntityUtils.consume(entity);
            return result;
        }
    }
 
    public  String get(String url) throws IOException {
        HttpGet httpget = new HttpGet(url);
        try (CloseableHttpResponse response = getHttpClient(url).execute(httpget,HttpClientContext.create())){
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);   //关闭HttpEntity是的流,如果手动关闭了InputStream instream = entity.getContent();这个流,也可以不调用这个方法
            return result;
        }
    }
    
    //用于监控空闲的连接池连接
    private static final class IdleConnectionMonitorThread extends Thread {
        private final HttpClientConnectionManager connMgr;
        private volatile boolean shutdown;
 
        private static final int MONITOR_INTERVAL_MS = 2000;
        private static final int IDLE_ALIVE_MS = 5000;
 
        public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
             super();
             this.connMgr = connMgr;
             this.shutdown = false;
             log.info("初始化监控线程");
        }
 
        @Override
        public void run() {
            try {
                while (!shutdown) {
                    synchronized (this) {
                        wait(MONITOR_INTERVAL_MS);
                        // 关闭无效的连接
                        connMgr.closeExpiredConnections();
                        // 关闭空闲时间超过IDLE_ALIVE_MS的连接
                        connMgr.closeIdleConnections(IDLE_ALIVE_MS, TimeUnit.MILLISECONDS);
                }
            }
            } catch (InterruptedException e) {
               log.error(e.getMessage(),e);
            }
        }
 
        // 关闭后台连接
        public void shutdown() {
            shutdown = true;
            synchronized (this) {
                notifyAll();
            }
        }
    }

    public static void main(String[] args){
        String url = "https://linkedin.com/company/stack-overflow";
        Map<String, String> headerMap = Maps.newHashMapWithExpectedSize(8);
        headerMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
        HttpClientUtil clientUtil = new HttpClientUtil();
        try {
            clientUtil.post(url,headerMap,"{}");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            clientUtil.post(url,headerMap,"{}");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值