这篇文章主要介绍“在SpringBoot中怎么缓存HTTP请求响应体”,在日常操作中,相信很多人在在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 : 请求体过大
因为限制了请求体的大小,这里日志中输出的请求体日志,就只有限制字节的大小了
到此,关于“在SpringBoot中怎么缓存HTTP请求响应体”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.xuebuyuan.com/3286932.html