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 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档