Home  >  Article  >  Spring boot WebFlux: WebFilter doesn't work

Spring boot WebFlux: WebFilter doesn't work

PHPz
PHPzforward
2024-02-09 09:30:31645browse

php Editor Banana introduced that Spring Boot WebFlux is a Web framework based on reactive programming, which provides an asynchronous and non-blocking way to process HTTP requests. However, sometimes we may encounter the problem that WebFilter does not work. WebFilter is a component used to perform certain actions before or after a request enters a web application. This article will explore the possible reasons why WebFilter is not working and provide solutions to ensure that WebFilter works properly in Spring Boot WebFlux.

Question content

I have the following controller which returns a mono

of a string
@restcontroller
@requestmapping("api/v1/test")
public class testcontroller {

    @postmapping
    public mono<string> getdraft() {
        return mono.just("ok");
    }

}

I added the bean webfilter to do some processing when the request comes, the problem is that the message in the bean is not displayed in the console, I tried adding breakpoints to debug, but when I test the api it does not stop at the breakpoint . In actuator/beans I found bean slf4jmdcfilter. Is there another configuration to add?

@Configuration
public class WebConfig {

    public static final String TRX_ID = "transactionId";
    public static final String PATH_URI = "pathUri";

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    WebFilter slf4jMdcFilter() {
        return (exchange, chain) -> {
            System.out.println("Filtering request");
            String requestId = exchange.getRequest().getId();
            return chain.filter(exchange)
                    .contextWrite(Context.of(TRX_ID, requestId)
                            .put(PATH_URI, exchange.getRequest().getPath()));
        };
    }

}

Solution

This can be done by using defercontextual(function) & transformdeferredcontextual(bifunction)

@Component
public class YourFilter implements WebFilter {

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    return Mono.deferContextual(contextView -> chain.filter(exchange)
        .contextWrite(context -> context.put("KEY", "VALUE")));
  }
}

// controller
 @Override
  public Mono<String> testApi(ServerWebExchange exchange) {
    return Mono.just("OK")
        .transformDeferredContextual((data, context) -> {
          log.info("context is {}", (Object) context.get("KEY"));
          return data;
        });
  }

The above is the detailed content of Spring boot WebFlux: WebFilter doesn't work. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete