這篇文章主要講解了“在SpringBoot中緩存HTTP請求響應體的方法”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“在SpringBoot中緩存HTTP請求響應體的方法”吧!
創新互聯堅持“要么做到,要么別承諾”的工作理念,服務領域包括:成都網站建設、成都網站制作、企業官網、英文網站、手機端網站、網站推廣等服務,滿足客戶于互聯網時代的三原網站設計、移動媒體設計的需求,幫助企業找到有效的互聯網解決方案。努力成為您成熟可靠的網絡建設合作伙伴!
把一個HTTP的請求,響應信息完整的紀錄到日志。是一種常見有效的問題排查,BUG重現的手段。
但是流這種東西,有一個特點就是只能讀取/寫入一次,不能重復。下一次讀寫,就是一個空的流,為了實現流的重用,就很有必要,把讀取和寫入的數據緩存起來, 可以在某個地方,再一次的讀取。
HttpServletRequestWrapper
HttpServletResponseWrapper
上面2個類,熟悉Servlet的都知道,這倆就是Request和Response的裝飾模式實現。
通過裝飾者設計模式,我們可以在Request讀取請求body的時候,把讀取到的數據復制一份緩存起來,記錄日志時使用。同理,也可以把Response響應的數據,先緩存起來,用于記錄日志,然后再響應給客戶端。
// 這里忽略了 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限制請求體大小。因為它默認把請求體緩存到內存中,如果客戶端發起惡意請求,構造大體積的請求體可能會消耗干凈服務器的內存
// 這里忽略了 HttpServletResponse 的相關方法
public class ContentCachingResponseWrapper {
// 把緩存中的響應數據,刷出到客戶端
void copyBodyToResponse()
// 獲取緩存數據
byte[] getContentAsByteArray()
// 獲取緩存數據
InputStream getContentInputStream()
// 獲取緩存數據的大小
int getContentSize()
}很簡單,通過ContentCachingResponseWrapper 的包裝,任何往客戶端的響應數據,都會被它緩存起來,重復的讀取使用,最終響應給客戶端
及其簡單,把請求體,添加時間戳后回寫給客戶端。
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輸出請求體/響應體,耗時,等等信息到日志。還對當前請求體生成了一個全局唯一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 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 : 請求體過大因為限制了請求體的大小,這里日志中輸出的請求體日志,就只有限制字節的大小了
源文:https://springboot.io/t/topic/3637
感謝各位的閱讀,以上就是“在SpringBoot中緩存HTTP請求響應體的方法”的內容了,經過本文的學習后,相信大家對在SpringBoot中緩存HTTP請求響應體的方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創新互聯,小編將為大家推送更多相關知識點的文章,歡迎關注!
名稱欄目:在SpringBoot中緩存HTTP請求響應體的方法
文章出自:http://www.yijiale78.com/article40/gddpho.html
成都網站建設公司_創新互聯,為您提供虛擬主機、品牌網站設計、網站維護、微信小程序、微信公眾號、商城網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯