緩存請求響應體的目的
把一個HTTP的請求,響應信息完整的紀錄到日志。是一種常見有效的問題排查,BUG重現的手段。
但是流這種東西,有一個特點就是只能讀取/寫入一次,不能重復。下一次讀寫,就是一個空的流,為了實現流的重用,就很有必要,把讀取和寫入的數據緩存起來, 可以在某個地方,再一次的讀取。
實現的思路
- HttpServletRequestWrapper
- HttpServletResponseWrapper
上面2個類,熟悉Servlet
的都知道,這倆就是Request
和Response
的裝飾模式實現。
通過裝飾者設計模式,我們可以在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) {
System.err.println(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 1ms
com.demo.web.filter.AccessLogFilter : POST /demo site=springboot.io&name=springboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA 200
com.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 1ms
com.demo.web.filter.AccessLogFilter : POST /demo site=springboot.io&name=springboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA 413
com.demo.web.filter.AccessLogFilter : {"name": "springboot"}{"name":
com.demo.web.filter.AccessLogFilter : 請求體過大
因為限制了請求體的大小,這里日志中輸出的請求體日志,就只有限制字節的大小了