SocketTimeoutException读取RestTemplate,PoolingHttpClientConnectionManager

时间:2017-08-08 13:15:01

标签: resttemplate requestfactory socket-timeout-exception

我正在努力解决读取超时异常。

对于API调用,我使用RestTemplate并且它运行良好,但是读取超时异常每天发生5~6次。 我花了一段时间来处理它,但我不知道我的Web服务有什么问题会导致读取超时异常。

这是我的代码,我使用Spring 4.3和HttpClient 4.5.2来使用PoolingHttpClientConnectionManager。

请帮助我。

@Component
public class TestClient {

private RestTemplate template;

private PoolingHttpClientConnectionManager manager;

private static Logger logger = LoggerFactory.getLogger(TestClient.class);

@PostConstruct
public void init() {
    this.manager = new PoolingHttpClientConnectionManager();
    this.manager.setMaxTotal(60);
    this.manager.setDefaultMaxPerRoute(30);
    this.manager.setValidateAfterInactivity(1000 * 30);

    CloseableHttpClient client = HttpClients.custom()
            .setConnectionManager(manager)
            .build();

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
    factory.setReadTimeout(1000 * 20);
    factory.setConnectionRequestTimeout(1000 * 10);
    factory.setConnectTimeout(1000 * 10);

    this.template = new RestTemplate(factory);
}

public Map<String, Object> exchange(String url, Object req, String tmonTid) {
    try {
        logger.info("Pool Stat [{}] {}", tmonTid, this.manager.getTotalStats().toString());
        RequestEntity<Object> request = RequestEntity.post(new URI(url))
                .contentType(MediaType.APPLICATION_JSON_UTF8).body(req);
        ResponseEntity<Map> ret = template.exchange(request, Map.class);

        if (HttpStatus.OK == ret.getStatusCode()) {
            return ret.getBody();
        } else {
            return MapUtils.EMPTY_MAP;
        }
    } catch (Exception e) {
       e.printStackTrace();
    }
}

}

0 个答案:

没有答案