Interceptor in Spring 5 WebFlux Interceptor in Spring 5 WebFlux spring spring

Interceptor in Spring 5 WebFlux


If you want to handle a request when it starts and when it completes, you can use WebFilter.

Try something like this

@Componentpublic 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. 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.

The feature you're describing sounds a lot like the metrics support provided by Actuator and Micrometer. If you'd like to try it:

  1. Add the actuator dependency to your project
  2. Expose the relevant endpoints (here, metrics)
  3. Go to "/actuator/metrics and select the metric for server HTTP requests (see the reference documentation).

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.

Note: adding spring-boot-starter-web to your application will turn it into a Spring MVC application.


Use the following project as dependency as 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>

It provides ReactiveApiInterceptor which is a custom implementation of WebFilter