duan5564712 2019-01-16 15:51 采纳率: 0%
浏览 472

http超时有些没有控制住

设置超时时间为3秒,大部分能控制住,但是还是有10秒或者10分钟以上的
麻烦大神帮忙看看,以下是使用的方法,

private static Logger logger = LoggerFactory.getLogger(SpringRestTemplateUtils.class);
    public static RestTemplate restTemplate;
    public static CloseableHttpClient client;
    public static HttpComponentsClientHttpRequestFactory factory;

    static{
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
         connMgr.setMaxTotal(2000);
         connMgr.setDefaultMaxPerRoute(500);
         client = HttpClients.custom()
              .setConnectionManager(connMgr)
              .build();
         factory = new HttpComponentsClientHttpRequestFactory(client);
         Thread thread = new Thread(new IdleConnectionMonitorThread(connMgr));
         thread.start();
    }

    /**
     * 
     * @param url 请求url
     * @param httpMethod 请求方式:HttpMethod.POST HttpMethod.GET
     * @param header 报文头设置
     * @param params JSON格式
     * @param readTimeOut 响应超时时间(单位:毫秒)
     * @param connectTimeOut 请求超时时间(单位:毫秒)
     * @return
     */
    public static String exchange(String url, HttpMethod httpMethod, HttpHeaders header, JSONObject params, int readTimeOut, int connectTimeOut){
        factory.setReadTimeout(readTimeOut);
        factory.setConnectTimeout(connectTimeOut);
        if(restTemplate == null){
              restTemplate = new RestTemplate(factory);
        }
        //MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8");
        //header.setContentType(type);
        HttpEntity<JSONObject> h = new HttpEntity<>(params, header);
        try {
             ResponseEntity<String> resp = restTemplate.exchange(url, httpMethod, h, String.class);
             return resp.getBody();
        }catch (HttpClientErrorException e) {
            return e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
           return e.getResponseBodyAsString();
        } catch (Exception e) {
            logger.error("#########远程请求原始异常",e);
            if(e.getCause() == null || (!(e.getCause() instanceof SocketTimeoutException) && !(e.getCause() instanceof ConnectTimeoutException))){
                restTemplate = null;
            }else{
                throw e;
            }
            return null;
        }
    }
  • 写回答

1条回答

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-21 01:55
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法