【问题标题】:Disconnecting from HttpURLConnection when returning an InputStream from a Webservice从 Web 服务返回 InputStream 时从 HttpURLConnection 断开连接
【发布时间】:2013-02-27 07:15:47
【问题描述】:
我有一个正在调用 Swift 集群的 Web 服务,发现与它的连接处于 CLOSE_WAIT 状态,直到 HA 代理强制关闭连接并记录事件后才关闭,导致大量要生成的事件。
对此我进行了调查,我发现这是由于在我们完成连接后没有断开与底层 HttpURLConnection 的连接。
所以我已经对我们的大多数 RESTful 服务进行了必要的更改,但我不确定在我们返回一个直接从 Swift 检索的 InputStream 的情况下,我应该如何断开与 HttpURLConnection 的连接。网络服务。
对于在这种情况下应该做什么我不知道或者任何人都可以想到在流被消耗后断开连接的任何好主意,是否有某种最佳实践?
谢谢。
【问题讨论】:
标签:
java
sockets
connection
inputstream
httpurlconnection
【解决方案1】:
我最终只是将 InputStream 包装在一个存储 HttpURLConnection 的对象中,并在读取完流后调用 disconnect 方法
public class WrappedInputStream extends InputStream{
InputStream is;
HttpURLConnection urlconn;
public WarppedInputStream(InputStream is, HttpURLConnection urlconn){
this.is = is;
this.urlconn = urlconn;
}
@Override
public int read() throws IOException{
int read = this.is.read();
if (read != -1){
return read;
}else{
is.close();
urlconn.disconnect();
return -1;
}
}
@Override
public int read(byte[] b) throws IOException{
int read = this.is.read(b);
if (read != -1){
return read;
}else{
is.close();
urlconn.disconnect();
return -1;
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException{
int read = this.is.read(b, off, len);
if (read != -1){
return read;
}else{
is.close();
urlconn.disconnect();
return -1;
}
}
}
【解决方案2】:
您不应该这样做。 HttpURLConnection 底层的连接池应该在少量几秒(我相信 15 秒)空闲时间后关闭底层 TCP 连接。通过调用disconnect(),您将完全禁用连接池,这会浪费更多的网络和服务器资源,因为每次调用都需要一个新的连接。