How to get the context of the current request in spring -webflux

In classic spring-mvc, you can set attributes with the scope of the request to RequestContextHolder. Based on this, we can analyze the incoming request in HandlerInterceptorAdapter, set the request parameters, such as the current user, a unique request identifier (for log correlation), etc. These request attributes can be obtained statically from any service (not just controllers) over the life of the request.

I am trying to achieve something similar with spring -webflux.

I could use WebFilterto intercept all incoming requests, get the current one ServerWebExchangeand set attributes on it. However, I see no way to get the current request ServerWebExchangeelsewhere than the controller methods.

I am looking for a better solution than passing ServerWebExchange(or ServerHttpRequest).

This seems to be difficult to achieve in webflux, because we cannot rely on saving the variables associated with a particular request for ThreadLocal (due to the non-blocking architecture, one thread can switch between requests in the middle of the flight).
However, this is an important requirement. Maybe there is a different approach?

+6
source share
1 answer

The approaches you describe are currently supported. As you emphasized, using a static approach is ThreadLocalsnot possible.

(. PR). Spring, , , , .

, , JIRA issue Spring Framework, - .

+2

Source: https://habr.com/ru/post/1017259/


All Articles