java 高并发下HttpClient连接池使用

 HttpClient连接池的使用,保持单例(不要创建多个连接池),高效连接,连接数需根据需求定。

import org.apache.commons.lang3.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.HttpPost;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
import java.nio.charset.StandardCharsets;
 
/**
 * Created by sms.reyo.cn
 */
public  class HttpSend {
 
    private PoolingHttpClientConnectionManager connPoolMng;
    private RequestConfig requestConfig;
    private volatile static HttpSend httpSendInstance;
    private static int maxTotal = 500;
 
    /**
     * 私有构造方法
     * 单例中连接池初始化一次
     */
    private HttpSend(){
        //初始化http连接池
        connPoolMng = new PoolingHttpClientConnectionManager();
        connPoolMng.setMaxTotal(maxTotal);
        connPoolMng.setDefaultMaxPerRoute(maxTotal/5);
        //初始化请求超时控制参数
        requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000) //连接超时时间
                .setConnectionRequestTimeout(5000) //从线程池中获取线程超时时间
                .setSocketTimeout(5000) //设置数据超时时间
                .build();
    }
 
    /**
     * 单例模式
     * 使用双检锁机制,线程安全且在多线程情况下能保持高性能
     * @return
     */
    public static HttpSend getInstance(){
        if(httpSendInstance == null){
            synchronized (HttpSend.class) {
                if(httpSendInstance == null){
                    httpSendInstance = new HttpSend();
                }
            }
        }
        return httpSendInstance;
    }
 
    /**
     * 获取client客户端
     * @return
     */
    public CloseableHttpClient getClient() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connPoolMng)
                .setDefaultRequestConfig(requestConfig)
                .build();
        return httpClient;
    }
 
    /**
     * httppost请求
     * @param postUrl
     * @param jsonStr
     * @return
     * @throws IOException
     */
    public String postRequest(String postUrl, String jsonStr) throws Exception {
        if (StringUtils.isBlank(postUrl)){
            return null;
        }
        HttpPost post = new HttpPost(postUrl);
        StringEntity myEntity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
        post.setEntity(myEntity);
        CloseableHttpResponse response = this.getClient().execute(post);
        if (response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, StandardCharsets.UTF_8);
        }
        return null;
    }
}

 

posted @ 2022-12-11 18:49  锐洋智能  阅读(1206)  评论(0编辑  收藏  举报