【问题标题】:Interceptor in Spring 5 WebFluxSpring 5 WebFlux 中的拦截器
【发布时间】:2018-04-15 22:42:45
【问题描述】:

我在我的项目中使用Spring WebFlux。我想创建一个拦截器来计算每个 API 所花费的时间。在Spring MVC 中,我们有HandlerInterceptor,它在spring-boot-starter-webflux 中不存在。我尝试添加spring-boot-starter-web 并编写了我的拦截器,但它没有用。代码如下:

@Component
public class TimeInterceptor implements HandlerInterceptor {

public static Logger logger = Logger.getLogger(TimeInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    long startTime = System.currentTimeMillis();
    request.setAttribute("startTime", startTime);
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    long totaltime = System.currentTimeMillis() - (long) request.getAttribute("startTime");
    request.setAttribute("totaltime", totaltime);
    logger.info("Logging total time" + totaltime);

}
...
...

我想为我的应用程序添加类似的功能并拦截每次调用所花费的时间。

提前致谢。

【问题讨论】:

    标签: spring spring-mvc spring-webflux


    【解决方案1】:

    Spring WebFlux 中没有HandlerInterceptor 的概念,但您可以使用自己的WebFilter 来代替。

    您描述的功能听起来很像 Actuator 和 Micrometer 提供的指标支持。如果你想试试:

    1. 将执行器依赖项添加到您的项目中
    2. 公开the relevant endpoints(这里是metrics
    3. 转到"/actuator/metrics 并选择服务器HTTP 请求的指标(请参阅the reference documentation)。

    Micrometer 提供了更多方法,可帮助您正确设置指标,例如:在测量时间时考虑 GC 暂停、提供直方图/百分位数/...等等。

    注意:将spring-boot-starter-web 添加到您的应用程序将把它变成一个Spring MVC 应用程序。

    【讨论】:

      【解决方案2】:

      如果你想在请求开始和完成时处理它,你可以使用WebFilter

      试试这样的

      @Component
      public class CustomWebFilter implements WebFilter {
          @Override
          public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
              long startTime = System.currentTimeMillis();
              return chain.filter(exchange).doFinally(signalType -> {
                  long totalTime = System.currentTimeMillis() - startTime;
                  exchange.getAttributes().put("totalTime", totalTime);
                  System.out.println(totalTime);
              });
          }
      }
      

      当请求处理开始时,所有定义的过滤器都会被调用。 Mono 从过滤器返回。它指示请求处理何时完成。

      【讨论】:

        【解决方案3】:

        使用以下项目作为jar / ant / maven / gradle的依赖

        https://github.com/TurquoiseSpace/spring-webflux-http-interceptor

        <dependency>
            <groupId>com.github.TurquoiseSpace</groupId>
            <artifactId>spring-webflux-http-interceptor</artifactId>
            <version>0.0.7</version>
        </dependency>
        

        它提供ReactiveApiInterceptor,这是WebFilter的自定义实现

        【讨论】:

          【解决方案4】:

          如果需要,您也可以覆盖ReactiveApiInterceptor,以添加您自己的自定义逻辑,除了具有默认逻辑,通过调用

          @Override
          public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
              // Your custom implementation, when api is hit and the request lands
              super.filter(serverWebExchange, webFilterChain)
                  .doFinally(signalType -> {
                      // Your custom implementation, when request-response exchange gets completed
                  });
          }
          

          【讨论】:

            猜你喜欢
            • 2023-03-13
            • 2018-08-09
            • 1970-01-01
            • 2014-05-19
            • 2017-02-25
            • 1970-01-01
            • 1970-01-01
            • 2015-10-21
            • 2018-03-05
            相关资源
            最近更新 更多