首页 文章

从Webservice返回InputStream时断开与HttpURLConnection的连接

提问于
浏览
0

我有一个Web服务正在调用Swift集群,并发现与它的连接处于CLOSE_WAIT状态,并且在HA代理强制关闭连接并记录事件之前不会关闭,导致大量事件发 生产环境 生 .

调查这个我发现这是因为我们完成连接后没有断开与底层HttpURLConnection的连接 .

所以我已经完成了对大多数RESTful服务的必要更改但是我不知道在我们返回一个直接从Web服务从Swift检索的InputStream的情况下我应该如何断开与HttpURLConnection的连接 .

在这个实例中我应该做些什么样的最佳实践是我不知道的,或者任何人都可以想到在流消耗后断开连接的任何好主意?

谢谢 .

2 回答

  • 0

    我最终只是将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;
                }
            }
        }
    
  • 0

    你不应该这样做 . 底层 HttpURLConnection 的连接池应该在一小段时间(我相信15秒)的空闲时间后关闭底层TCP连接 . 通过调用 disconnect() ,您将完全禁用连接池,这会通过每次调用需要新连接来浪费更多网络和服务器资源 .

相关问题