我有app继续为json数据调用api,很快我就看到了'Timeout等待来自池的连接'异常,我用Google搜索并发现内容未被消耗导致连接泄漏,所以我更新了使用jsondata后关闭输入流的代码,但仍然得到那些连接超时异常,这是我的代码:
InputStream is = ApiUtil.getAsStream(Api.get(bookUrl).param("limit","500").param("bookId", bid).enable(Options.LongRunning), 3);
List<JsonBook> books = mapper.readValue(is, BOOK_TYPE);
is.close()
Api:
private JsonHttpClient client;
public APIForGet get(String endpoint) {
return new APIForGet(this.client, endpoint);
}
ApiUtil:
public static InputStream getAsStream(APIForGet get, Iterable<Long>retries) {
return get.asStream();
}
APIForGet:
private JsonHttpClient client;
public InputStream asStream() {
return this.client.getAsStream(this.hostname, this.port, this.endpoint, params, optionsArray());
}
JsonHttpClientImpl:
public InputStream getAsStream(Optional<String> host, Optional<Integer> port,String path, Multimap<String, String> param, Options ... options) {
HttpResponse reponse;
try {
response = request.execute();
if (response.isSuccessStatusCode()) {
return response.getContent();
}
} catch (Exception e) {
throw new Exception();
}
}
这里的包装逻辑有点复杂,但最终我认为通过关闭输入流应该工作,任何想法?谢谢!
答案 0 :(得分:0)
try {
response = request.execute();
if (response.isSuccessStatusCode()) {
return response.getContent();
}
} catch (Exception e) {
throw new Exception();
}finally{
//TODO release conn or abort
}