In the classic spring-mvc it is possible to set request scoped attributes on a RequestContextHolder
. Building on that, we can parse an incoming request in a HandlerInterceptorAdapter
, set request parameters such as currently logged in user, unique request ID (for log correlation) and so on.
These request attributes can be retrieved statically from any service (not only controllers) during the request's lifetime.
I am trying to achieve something similar with spring-webflux.
I could use a WebFilter
to intercept all incoming requests, get the current ServerWebExchange
and set attributes on it. However I don't see any way to get the current request's ServerWebExchange
anywhere else other than controller methods.
I am looking for a better solution than passing ServerWebExchange
(or ServerHttpRequest
) all around.
It seems like this is difficult to achieve in webflux since we cannot rely on saving variables associated with a particular request on ThreadLocal (because of the non-blocking architecture, a single thread can switch between requests mid-flight).
Still, this is an important requirement. Maybe there is a different approach?
public interface ServerWebExchange. Contract for an HTTP request-response interaction. Provides access to the HTTP request and response and also exposes additional server-side processing related properties and features such as request attributes.
How to extract data from Flux in Java? Another way would be using the Reactive Streams operators like onNext, flatMap, etc. In the below example, we are using the onNext() method to get data from Flux and print it. Note: We need to subscribe to the Publisher.
There are several reasons for this: Spring MVC can't run on Netty. both infrastructure will compete for the same job (for example, serving static resources, the mappings, etc) mixing both runtime models within the same container is not a good idea and is likely to perform badly or just not work at all.
What is Spring WebFlux ? Spring WebFlux is parallel version of Spring MVC and supports fully non-blocking reactive streams. It support the back pressure concept and uses Netty as inbuilt server to run reactive applications. If you are familiar with Spring MVC programming style, you can easily work on webflux also.
The approaches you're describing are the ones currently supported.
As you've underlined, using a static approach with ThreadLocals
is not possible.
Reactor is looking into alternatives with a new context feature (see this PR). Spring is likely to pick that up and use it, but not necessarily for request attributes since the current model fits quite well.
If you'd like a particular extension point to intercept requests, please create a JIRA issue on the Spring Framework project, describing what you're trying to achieve and where things are failing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With