2013-03-11 42 views
0

我有一个Web服务正在调用Swift集群,并发现它的连接处于CLOSE_WAIT状态,直到HA代理强制关闭连接才关闭并记录事件,导致生成大量事件。当从Webservice返回InputStream时断开与HttpURLConnection的连接

调查了一下,我发现这是因为我们完成了连接后没有断开与底层HttpURLConnection的连接。

因此,我已经通过了对大多数RESTful服务的必要更改,但是我不确定在我们返回从Swift检索的InputStream的情况下,我应该如何从HttpURLConnection中断开连接web服务。

有没有什么应该做的事情的最佳做法,我不知道或没有人能想到任何人想在流被消费后断开任何好的想法?

谢谢。

回答

0

我最终只是包裹的InputStream在存储HttpURLConnection的还有,一旦读取完流

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的连接池应该在短暂的几秒钟后关闭底层的TCP连接,我相信15秒的空闲时间。通过调用disconnect(),您将完全禁用连接池,因为每次调用都需要新的连接,从而浪费更多的网络和服务器资源。

相关问题