如何在spring拦截器中使用异步服务?

wwwo4jvm  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(197)

我想在我自己的实现中记录http请求/响应数据 HandlerInterceptor 并用 @Async 带注解的方法(避免阻塞主线程)。
拦截器被正确调用,但当发生异常时,在拦截器get correctly 500内部服务器错误 HttpServletResponse ,但在 @Async 方法get http status 200 ok。

public class LoggingInterceptor implements AsyncHandlerInterceptor {

  private static Logger LOGGER = LogManager.getLogger(LoggingInterceptor.class);

  private final AsyncLogRequestInfoSaver saver;

  public LoggingInterceptor(final AsyncLogRequestInfoSaver saver) {
    this.saver = saver;
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    LOGGER.debug("HTTP status code: {}", response.getStatus()); // Here I got HTTP 500
    this.saver.save(request, response);

  }
}

异步方法:

@Service
public class AsyncLogRequestInfoSaver {

      @Async
    public void save(final HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {

        LOGGER.debug("HTTP status code: {}", response.getStatus()); // Here I got HTTP 200

    }

}

我做错什么了?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题