Reputation: 163
I am struggling with Read timed out exception.
For API call, I am using RestTemplate and it works pretty well, but the read timed out exception occured 5~6 times a day. I've spend for a while to deal with it, but I have no idea what problem of my web service causes the read timed out exception.
Here is my code and I am using Spring 4.3 and HttpClient 4.5.2 to use PoolingHttpClientConnectionManager.
Please, help me.
@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();
}
}
}
Upvotes: 4
Views: 834