org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool异常处理

本文介绍了在处理高并发情况下如何通过Spring框架中的RestTemplate进行HTTP请求的优化,包括创建RestTemplateConfig类、配置HttpClient以管理连接池和超时时间,以及使用PLCHttpsUtils工具类进行HTTP操作的封装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

出现这个问题是由于并发量大,不断向服务器发起请求。优化HTTP调用接口代码

1.编写RestTemplateConfig 类

package com.tqjc.system.core.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(httpRequestFactory());
    }


    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }


    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        //设置整个连接池最大连接数
        connectionManager.setMaxTotal(50);
//50  20
        //路由是对maxTotal的细分
        connectionManager.setDefaultMaxPerRoute(25);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)  //返回数据的超时时间
                .setConnectTimeout(10000) //连接上服务器的超时时间
                .setConnectionRequestTimeout(1000) //从连接池中获取连接的超时时间
                .build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}

2.编写HTTP工具类,使用RestTemplate 进行HTTP连接

package com.tqjc.system.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tqjc.system.common.constant.ConfigConstant;
import com.tqjc.system.common.constant.GlobalConstant;
import com.tqjc.system.common.constant.RemoteURLConstant;
import com.tqjc.system.common.entity.BO.PLCWriteRequestParamBO;
import com.tqjc.system.common.entity.BO.ResponseLabelDataBO;
import com.tqjc.system.system.util.SystemUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @description:
 * @Author: 86195
 * @Date: 2023/12/27 22:41
 **/
@Slf4j
public class PLCHttpsUtils {


    public static RestTemplate restTemplate;

    static {
        RestTemplate bean = SpringUtils.getBean(RestTemplate.class);
        restTemplate = bean;
    }


    public static void writeMoreVal(String url, PLCWriteRequestParamBO paramBO) {
        HttpHeaders headers = new HttpHeaders();
        Map<String, Object> body = new HashMap<>();
        body.put("mac_sn", paramBO.getMacSN());
        body.put("address", paramBO.getAddress());
        body.put("dataType", paramBO.getDataType());
        body.put("values", paramBO.getValue());
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity httpEntity = new HttpEntity<>(body, headers);
        restTemplate.postForObject(url, httpEntity, String.class);
    }




    public static <T> T sendPost(String url, Map body, Class<T> t) {
        T res = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Accept", "application/json");
            HttpEntity httpEntity = new HttpEntity<>(body, headers);
            String resultPost = restTemplate.postForObject(url, httpEntity, String.class);
            res = JSONObject.parseObject(resultPost, t);
        } catch (Exception e){
            log.error("HttpsUtils sendPost running error,接口调用异常",e);
            throw e;
        }
        return res;
    }






    public static void write(String url, PLCWriteRequestParamBO paramBO) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        Map<String, Object> body = new HashMap<>();
        body.put("mac_sn", paramBO.getMacSN());
        body.put("address", paramBO.getAddress());
        body.put("dataType", paramBO.getDataType());
        body.put("values", paramBO.getValue());
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity httpEntity = new HttpEntity<>(body, headers);
        int i = 0;
        while (true){
            try {
                restTemplate.postForObject(url, httpEntity, String.class);
                Thread.sleep(300);
                //读值操作
                Map<String,String> paramMap = new HashMap(2);
                Map<String, String> snMap = SystemUtils.Sys_carInfo.get(ConfigConstant.CONFIG_TYPE_CAR_BAK_SN);
                String sn = snMap.get(paramBO.getMacSN());
                paramMap.put(GlobalConstant.STRING_LABEL,paramBO.getLabel());
                paramMap.put(GlobalConstant.STRING_SN,sn);
                ResponseLabelDataBO res = PLCHttpsUtils.sendPost(RemoteURLConstant.URL_READBC, paramMap, ResponseLabelDataBO.class);
                Map<String, String> content = res != null? res.getContent(): null;

                if(content != null){
                    String currentVal = content.get("currentVal") != null ?
                            content.get("currentVal").toLowerCase() : null;
                    if(Objects.equals(currentVal,paramBO.getValue())){
                        //标定完成后,跳出循环
                        break;
                    }
                }
                i++;
                if(i > 3){
                    throw new Exception("写值操作超过三次");
                }

            } catch (Exception e){
                log.error("HttpsUtils write running error,接口调用异常",e);
                throw e;
            }

        }
    }


    public static boolean valIsSuccess(String sn,String label,String targetVal) throws IOException {
        Map<String,String> paramMap = new HashMap(2);
        paramMap.put(GlobalConstant.STRING_LABEL,label);
        paramMap.put(GlobalConstant.STRING_SN,sn);
        ResponseLabelDataBO res = PLCHttpsUtils.sendPost(RemoteURLConstant.URL_READBC, paramMap, ResponseLabelDataBO.class);
        Map<String, String> content = res != null? res.getContent(): null;
        if(content != null){
            String currentVal = content.get("currentVal") != null ?
                    content.get("currentVal").toLowerCase() : null;
            if(Objects.equals(currentVal,targetVal)){
                return true;
            }
        }

        return false;

    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值