ContentCachingRequestWrapper實現(xiàn)Request對象的可重復讀(引發(fā)OOM)

InputStream流本身是單向的,無法重復讀取,為了實現(xiàn)流的可重復讀,需要對流進行裝飾。但是對流的裝飾,卻引發(fā)了系統(tǒng)OOM

裝飾方案:

public class AdBizTraceLogFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        ContentCachingRequestWrapper reqWrapper = getRequestWrapper(request);
        response = getResponseWrapper(response);

        try {
            filterChain.doFilter(reqWrapper, response);
        } finally {
            // 業(yè)務(wù)層讀取一次body后, 后續(xù)都通過getContentAsByteArray讀取
            String reqBody = new String(reqWrapper.getContentAsByteArray(), "UTF-8");
            ContentCachingResponseWrapper respWrapper = (ContentCachingResponseWrapper) response;
            String respBody = new String(respWrapper.getContentAsByteArray(), "UTF-8");
            respWrapper.copyBodyToResponse();
        }

    }

    private ContentCachingRequestWrapper getRequestWrapper(HttpServletRequest request) {
        ContentCachingRequestWrapper requestWrapper;
        //此處有bug,會導致大數(shù)據(jù)的請求或者響應(yīng)對象的占用雙份內(nèi)存!?。?        if (request instanceof ContentCachingRequestWrapper) {
            requestWrapper = (ContentCachingRequestWrapper) request;
        } else {
            requestWrapper = new ContentCachingRequestWrapper(request);
        }
        return requestWrapper;
    }

    private ContentCachingResponseWrapper getResponseWrapper(HttpServletResponse response) {
        ContentCachingResponseWrapper responseWrapper;
        if (response instanceof ContentCachingResponseWrapper) {
            responseWrapper = (ContentCachingResponseWrapper) response;
        } else {
            responseWrapper = new ContentCachingResponseWrapper(response);
        }
        return responseWrapper;
    }

}

將流裝飾成可重復讀的流。但是如果系統(tǒng)存在大批量文件上傳,需要做一下控制,判斷contentType。

        if (request.getContentLength() > MAX_CONTENT_LENGTH) {
            PerfUtils.perf(LOG_NS, "ignorePath", "max length").logstash();
            return true;
        }

        String contentType = request.getHeader("Content-Type");
        if (contentType == null || !contentType.toLowerCase().contains("application/json")) {
            PerfUtils.perf(LOG_NS, "ignorePath", "content type").logstash();
            return true;
        }

在新版的Spring中ContentCachingRequestWrapper中使用FastByteArrayOutputStream來取代ContentCachingRequestWrapper,不需要初始化ContentCachingRequestWrapper的時候就申請大塊內(nèi)存,lazy化的。

https://github.com/spring-projects/spring-framework/commit/f83c6094362b7e16fe08a4307cbcb0015e203d23

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容