简体   繁体   English

Spring 5 WebFlux 中的拦截器

[英]Interceptor in Spring 5 WebFlux

I am using Spring WebFlux in my project.我在我的项目中使用Spring WebFlux I want to create an interceptor to calculate the time taken by each API.我想创建一个拦截器来计算每个 API 所花费的时间。 In Spring MVC we have HandlerInterceptor which is not present in spring-boot-starter-webflux .Spring MVC我们有HandlerInterceptor ,它在spring-boot-starter-webflux不存在。 I tried adding spring-boot-starter-web and wrote my interceptor but it didn't work.我尝试添加spring-boot-starter-web并编写了我的拦截器,但没有用。 Here is the code:这是代码:

@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);

}
...
...

I want to add similar functionality to my application and intercept time taken by each call.我想向我的应用程序添加类似的功能并拦截每次调用所花费的时间。

Thanks in advance.提前致谢。

If you want to handle a request when it starts and when it completes, you can use WebFilter .如果要在请求开始和完成时处理请求,可以使用WebFilter

Try something like this尝试这样的事情

@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);
        });
    }
}

When request processing starts all defined filters are called.当请求处理开始时,所有定义的过滤器都会被调用。 Mono is returned from filter. Mono 从过滤器返回。 It indicates when request processing is complete.它指示请求处理何时完成。

There is no concept of HandlerInterceptor in Spring WebFlux, but you can use your own WebFilter for that instead. Spring WebFlux 中没有HandlerInterceptor概念,但您可以使用自己的WebFilter来代替。

The feature you're describing sounds a lot like the metrics support provided by Actuator and Micrometer.您所描述的功能听起来很像 Actuator 和 Micrometer 提供的指标支持。 If you'd like to try it:如果你想试试:

  1. Add the actuator dependency to your project将执行器依赖项添加到您的项目中
  2. Expose the relevant endpoints (here, metrics )公开相关端点(此处为metrics
  3. Go to "/actuator/metrics and select the metric for server HTTP requests (see the reference documentation ).转到"/actuator/metrics并选择服务器 HTTP 请求的指标(请参阅参考文档)。

Micrometer offers way more and helps you to get your metrics right, like: taking into account GC pauses when measuring time, providing histograms/percentiles/..., and more. Micrometer 提供了更多方法并帮助您获得正确的指标,例如:在测量时间时考虑 GC 暂停,提供直方图/百分位数/...等。

Note: adding spring-boot-starter-web to your application will turn it into a Spring MVC application.注意:将spring-boot-starter-web到您的应用程序将把它变成一个 Spring MVC 应用程序。

Use the following project as dependency as jar / ant / maven / gradle使用如下项目作为依赖为jar / ant / maven / gradle

https://github.com/TurquoiseSpace/spring-webflux-http-interceptor 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>

It provides ReactiveApiInterceptor which is a custom implementation of WebFilter它提供了ReactiveApiInterceptor ,它是WebFilter的自定义实现

If required, you can override ReactiveApiInterceptor as well, to add your own custom logic, besides having the default logic, by calling如果需要,您也可以覆盖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
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM