其他
如何优雅记录 HTTP 请求/ 响应数据?
ContentCachingRequestWrapper ContentCachingResponseWrapper。
public abstract class HttpBodyRecorderFilter extends OncePerRequestFilter {
private static final int DEFAULT_MAX_PAYLOAD_LENGTH = 1024 * 512;
private int maxPayloadLength = DEFAULT_MAX_PAYLOAD_LENGTH;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
boolean isFirstRequest = !isAsyncDispatch(request);
HttpServletRequest requestToUse = request;
if (isFirstRequest && !(request instanceof ContentCachingRequestWrapper)
&& (request.getMethod().equals(HttpMethod.PUT.name())
|| request.getMethod().equals(HttpMethod.POST.name()))) {
requestToUse = new ContentCachingRequestWrapper(request);
}
HttpServletResponse responseToUse = response;
if (!(response instanceof ContentCachingResponseWrapper) && (request.getMethod().equals(HttpMethod.PUT.name())
|| request.getMethod().equals(HttpMethod.POST.name()))) {
responseToUse = new ContentCachingResponseWrapper(response);
}
boolean hasException = false;
try {
filterChain.doFilter(requestToUse, responseToUse);
} catch (final Exception e) {
hasException = true;
throw e;
} finally {
int code = hasException ? 500 : response.getStatus();
if (!isAsyncStarted(requestToUse) && (this.codeMatched(code, AdvancedHunterConfigManager.recordCode()))) {
recordBody(createRequest(requestToUse), createResponse(responseToUse));
} else {
writeResponseBack(responseToUse);
}
}
}
protected String createRequest(HttpServletRequest request) {
String payload = "";
ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
payload = genPayload(payload, buf, wrapper.getCharacterEncoding());
}
return payload;
}
protected String createResponse(HttpServletResponse resp) {
String response = "";
ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(resp, ContentCachingResponseWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
try {
wrapper.copyBodyToResponse();
} catch (IOException e) {
e.printStackTrace();
}
response = genPayload(response, buf, wrapper.getCharacterEncoding());
}
return response;
}
protected void writeResponseBack(HttpServletResponse resp) {
ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(resp, ContentCachingResponseWrapper.class);
if (wrapper != null) {
try {
wrapper.copyBodyToResponse();
} catch (IOException e) {
LOG.error("Fail to write response body back", e);
}
}
}
private String genPayload(String payload, byte[] buf, String characterEncoding) {
if (buf.length > 0 && buf.length < getMaxPayloadLength()) {
try {
payload = new String(buf, 0, buf.length, characterEncoding);
} catch (UnsupportedEncodingException ex) {
payload = "[unknown]";
}
}
return payload;
}
public int getMaxPayloadLength() {
return maxPayloadLength;
}
private boolean codeMatched(int responseStatus, String statusCode) {
if (statusCode.matches("^[0-9,]*$")) {
String[] filteredCode = statusCode.split(",");
return Stream.of(filteredCode).map(Integer::parseInt).collect(Collectors.toList()).contains(responseStatus);
} else {
return false;
}
}
protected abstract void recordBody(String payload, String response);
protected abstract String recordCode();
}
class PatternMappingFilterProxy implements Filter {
private final Filter delegate;
private final List<String> pathUrlPatterns = new ArrayList();
private PathMatcher pathMatcher;
public PatternMappingFilterProxy(Filter delegate, String... urlPatterns) {
Assert.notNull(delegate, "A delegate Filter is required");
this.delegate = delegate;
int length = urlPatterns.length;
pathMatcher = new AntPathMatcher();
for (int index = 0; index < length; ++index) {
String urlPattern = urlPatterns[index];
this.pathUrlPatterns.add(urlPattern);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getRequestURI();
if (this.matches(path)) {
this.delegate.doFilter(request, response, filterChain);
} else {
filterChain.doFilter(request, response);
}
}
private boolean matches(String requestPath) {
for (String pattern : pathUrlPatterns) {
if (pathMatcher.match(pattern, requestPath)) {
return true;
}
}
return false;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.delegate.init(filterConfig);
}
@Override
public void destroy() {
this.delegate.destroy();
}
public List<String> getPathUrlPatterns() {
return pathUrlPatterns;
}
public void setPathUrlPatterns(List<String> urlPatterns) {
pathUrlPatterns.clear();
pathUrlPatterns.addAll(urlPatterns);
}
}
@PostMapping("/test/{id}")
public Object test(@PathVariable(value = "id",required = true) final Integer index) {
//do something
}
/test/{id:[0-9]+}
。推荐阅读
你好,我是程序猿DD,10年开发老司机、阿里云MVP、腾讯云TVP、出过书创过业、国企4年互联网6年。从普通开发到架构师、再到合伙人。一路过来,给我最深的感受就是一定要不断学习并关注前沿。只要你能坚持下来,多思考、少抱怨、勤动手,就很容易实现弯道超车!所以,不要问我现在干什么是否来得及。如果你看好一个事情,一定是坚持了才能看到希望,而不是看到希望才去坚持。相信我,只要坚持下来,你一定比现在更好!如果你还没什么方向,可以先关注我,这里会经常分享一些前沿资讯,帮你积累弯道超车的资本。