使用ContentCachingResponseWrapper时未获取响应正文

时间:2020-04-21 12:45:09

标签: spring-boot spring-mvc spring-async spring-filter

我在Scala中有一个具有多个端点的Springboot API。所有端点都是异步的,并返回DeferredResult。在某些情况下,我想使用过滤器记录响应正文。我创建了一个过滤器,其中的命令1用于缓存请求和响应,如下所示:

@Component
@Order(1)
class ContentCachingFilter extends OncePerRequestFilter {
  override def doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain): Unit = {
    val requestToCache  = new ContentCachingRequestWrapper(request)
    val responseToCache = new ContentCachingResponseWrapper(response)
    filterChain.doFilter(requestToCache, responseToCache)
    responseToCache.copyBodyToResponse()
  }
}

我的日志记录过滤器类似于以下内容(已删除域特定的逻辑):

@Component
@Order(2)
class RequestResponseLoggingFilter extends OncePerRequestFilter {

  override def doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain): Unit = {

    logger.info(
      s"Request -> URL : ${request.getMethod} ${request.getRequestURI} ${request.getParameterMap.asScala.stringRepresentation()}")
    logger.debug(
      s"Request Headers -> Content-type : ${request.getContentType} \\n Headers : ${new ServletServerHttpRequest(request).getHeaders}")

    filterChain.doFilter(request, response)

    logger.info(s"Response -> Status : ${response.getStatus}")

  }
}

我必须使用ContentCachingResponseWrapper,因为我想记录响应正文。但是,即使不尝试记录响应正文,也只是通过引入ContentCachingResponseWrapper,对于任何端点的调用我都没有得到任何响应。本地正在运行的实例在curl上返回如下输出:

HTTP/1.1 200
Content-Type: application/json
Content-Length: 197
.
.
.
<
* transfer closed with 197 bytes remaining to read
* stopped the pause stream!
* Closing connection 0
curl: (18) transfer closed with 197 bytes remaining to read

如果删除ContentCachingFilter,则上面的日志过滤器可以正常工作,但是如果我尝试记录响应正文,则将消耗响应流,并且不再生成响应。 因此,我需要使用ContentCachingFilter

我确实发现,如果端点是同步的,那么所有这些都可以工作。 有人可以帮我找出问题所在,以及如何使它与异步端点一起工作。

1 个答案:

答案 0 :(得分:0)

val requestToCache = new ContentCachingRequestWrapper(request);
val responseToCache = new ContentCachingResponseWrapper(response);

这两行更改为:

  if(!(request instanceof ContentCachingRequestWrapper)) {
     requestToCache = new ContentCachingRequestWrapper(request);
  }
  if(!(request instanceof ContentCachingResponseWrapper)){
     responseToCache = new ContentCachingResponseWrapper(request);
  }