一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

ShallowEtagHeaderFilter大文件下载出现Out of memory解决办法

时间:2014-12-21 编辑:简简单单 来源:一聚教程网

最近解决大文件下载的问题,遇到一个"Out of memory"的exception。建厂controller层的代码,发现是用BufferdOutputStream写入Response中的,缓冲区也只有8m,按理说不应该出现内存溢出的。

仔细观察异常堆栈,发现堆栈中出现了“ShallowEtagHeaderFilter ”这个拦截器。该拦截器是用来处理ETag信息的。关于Etag和该拦截器的介绍可参考:
摘自百度百科:
http://baike.baidu.com/view/3039264.htm
ShallowEtagHeaderFilter介绍:
http://blog.csdn.net/geloin/article/details/7445251

阅读代码发现问题就出在这个过滤器中,这个过滤器中会将Buffered流转换成ByteArray流写入Response。而ByteArrayOutputStream都存储内存中,还需要频繁的扩容。这在大文件下载的时候自然会内存溢出。

解决方案

考虑到大部分url还是需要该拦截器进行过滤的,只是需要排除掉跟文件下载相关的url。所以这里OneCoder决定复写该Filter,设置一个黑名单,复写其中的doFilterInternal方法,对于黑名单中的url都直接传递给下一个filter,否则super一下,继续走原来的逻辑。

 代码如下 复制代码
/**
 * The filter is used for resolving the big file download problem when using
 * {@link ShallowEtagHeaderFilter}. The urls on the black list will be passed
 * directly to the next filter in the chain, the others will be filtered as
 * before.
 *


 * Sample:

 * {@code }

 *     {@codeBigFileEtagFilter}

 *    
 * {@codecom.coderli.filter.BigFileDownloadEtagHeaderFilter}

 *     {@code