缓存申请响应体的目标

把一个HTTP的申请,响应信息残缺的纪录到日志。是一种常见无效的问题排查,BUG重现的伎俩。

然而这种货色,有一个特点就是只能读取/写入一次,不能反复。下一次读写,就是一个空的流,为了实现流的重用,就很有必要,把读取和写入的数据缓存起来, 能够在某个中央,再一次的读取。

实现的思路

  • HttpServletRequestWrapper
  • HttpServletResponseWrapper

下面2个类,相熟Servlet的都晓得,这俩就是RequestResponse的装璜模式实现。

通过装璜者设计模式,咱们能够在Request读取申请body的时候,把读取到的数据复制一份缓存起来,记录日志时应用。同理,也能够把Response响应的数据,先缓存起来,用于记录日志,而后再响应给客户端。

Spring提供的实现

ContentCachingRequestWrapper

// 这里疏忽了 HttpServletRequest 的相干办法public class ContentCachingRequestWrapper extends HttpServletRequestWrapper  {    // 包装Servlet,不限度申请体的大小    public ContentCachingRequestWrapper(HttpServletRequest request)    // 包装Servlet,限度申请体的大小    public ContentCachingRequestWrapper(HttpServletRequest request, int contentCacheLimit)    // 获取到缓存的申请体    public byte[] getContentAsByteArray()    // 申请体超过限度时会调用这个办法,默认空实现    protected void handleContentOverflow(int contentCacheLimit) }

比拟好了解的一个类,倡议通过contentCacheLimit限度申请体大小。因为它默认把申请体缓存到内存中,如果客户端发动歹意申请,结构大体积的申请体可能会耗费洁净服务器的内存

ContentCachingResponseWrapper

// 这里疏忽了 HttpServletResponse 的相干办法public class ContentCachingResponseWrapper {    // 把缓存中的响应数据,刷出到客户端    void copyBodyToResponse()    // 获取缓存数据    byte[] getContentAsByteArray()    // 获取缓存数据    InputStream getContentInputStream()    // 获取缓存数据的大小    int getContentSize()}

很简略,通过ContentCachingResponseWrapper 的包装,任何往客户端的响应数据,都会被它缓存起来,反复的读取应用,最终响应给客户端

申请日志的实现

Controller

及其简略,把申请体,增加工夫戳后回写给客户端。

import java.util.HashMap;import java.util.Map;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/demo")public class DemoController {        @RequestMapping(produces = { "application/json; charset=utf-8" })    public Object demo (@RequestBody(required = false) String body) {        Map<String, Object> response = new HashMap<>();        response.put("reqeustBody", body);        response.put("timesttamp", System.currentTimeMillis());        return response;    }}

AccessLogFilter

通过AccessLogFilter输入申请体/响应体,耗时,等等信息到日志。还对以后申请体生成了一个全局惟一request-id,能够作为检索的条件。

import java.io.IOException;import java.nio.charset.StandardCharsets;import java.util.UUID;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpFilter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.core.annotation.Order;import org.springframework.http.MediaType;import org.springframework.stereotype.Component;import org.springframework.web.util.ContentCachingRequestWrapper;import org.springframework.web.util.ContentCachingResponseWrapper;import org.springframework.web.util.NestedServletException;@Component@WebFilter(filterName = "accessLogFilter", urlPatterns = "/*")@Order(-9999)         // 保障最先执行public class AccessLogFilter extends HttpFilter {        private static final Logger LOGGER = LoggerFactory.getLogger(AccessLogFilter.class);        private static final long serialVersionUID = -7791168563871425753L;        // 音讯体过大    @SuppressWarnings("unused")    private static class PayloadTooLargeException extends RuntimeException {        private static final long serialVersionUID = 3273651429076015456L;        private final int maxBodySize;        public PayloadTooLargeException(int maxBodySize) {            super();            this.maxBodySize = maxBodySize;        }    }    @Override    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {                ContentCachingRequestWrapper cachingRequestWrapper = new ContentCachingRequestWrapper(req, 30) { // 限度30个字节            @Override            protected void handleContentOverflow(int contentCacheLimit) {                throw new PayloadTooLargeException(contentCacheLimit);            }        };                ContentCachingResponseWrapper cachingResponseWrapper = new ContentCachingResponseWrapper(res);                        long start = System.currentTimeMillis();        try {            // 执行申请链            super.doFilter(cachingRequestWrapper, cachingResponseWrapper, chain);        } catch (NestedServletException e) {            Throwable cause = e.getCause();            // 申请体超过限度,以文本模式给客户端响应异样信息提醒            if (cause instanceof PayloadTooLargeException) {                cachingResponseWrapper.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);                cachingResponseWrapper.setContentType(MediaType.TEXT_PLAIN_VALUE);                cachingResponseWrapper.setCharacterEncoding(StandardCharsets.UTF_8.displayName());                cachingResponseWrapper.getOutputStream().write("申请体过大".getBytes(StandardCharsets.UTF_8));            } else {                throw new RuntimeException(e);            }        }                long end = System.currentTimeMillis();                String requestId = UUID.randomUUID().toString();        // 生成惟一的申请ID        cachingResponseWrapper.setHeader("x-request-id", requestId);                String requestUri = req.getRequestURI();        // 申请的        String queryParam = req.getQueryString();        // 查问参数        String method = req.getMethod();                // 申请办法        int status = cachingResponseWrapper.getStatus();// 响应状态码                // 申请体        // 转换为字符串,在限度申请体大小的状况下,因为字节数据不残缺,这里可能乱码,        String requestBody = new String(cachingRequestWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);            // 响应体        String responseBody = new String(cachingResponseWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);                LOGGER.info("{} {}ms", requestId, end - start);        LOGGER.info("{} {} {} {}", method, requestUri, queryParam, status);        LOGGER.info("{}", requestBody);        LOGGER.info("{}", responseBody);                // 这一步很重要,把缓存的响应内容,输入到客户端        cachingResponseWrapper.copyBodyToResponse();    }}

演示

失常申请和日志

com.demo.web.filter.AccessLogFilter      : a53500bc-c003-414a-9add-99655295a34f 1mscom.demo.web.filter.AccessLogFilter      : POST /demo site=springboot.io&name=springboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA 200com.demo.web.filter.AccessLogFilter      : {"name": "springboot"}com.demo.web.filter.AccessLogFilter      : {"reqeustBody":"{\"name\": \"springboot\"}","timesttamp":1620395056498}

体积超过限度的申请和日志

com.demo.web.filter.AccessLogFilter      : 99476161-1790-48cc-86b9-0641efadc1b5 1mscom.demo.web.filter.AccessLogFilter      : POST /demo site=springboot.io&name=springboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA 413com.demo.web.filter.AccessLogFilter      : {"name": "springboot"}{"name":com.demo.web.filter.AccessLogFilter      : 申请体过大
因为限度了申请体的大小,这里日志中输入的申请体日志,就只有限度字节的大小了

源文:https://springboot.io/t/topic...