Skip to content

RequestContextHolder for Reactive Web [SPR-15680] #20239

Closed
@spring-projects-issues

Description

@spring-projects-issues

Doron Gold opened SPR-15680 and commented

It is necessary to have a way to associate attributes with the current request and be able to fetch these attributes during the request lifetime.

The ability to set and get such attributes is essential for use-cases such as:

  • Having a unique trace-id per request, which can be included in all log messages.
  • Identifying the currently logged in user (the user associated with the request).
  • In a micro-service architecture: receiving contextual data via request headers, then when calling other micro-services, pass the same contextual data that came with the original request.

In webmvc this is possible by calling a static methods on org.springframework.web.context.request.RequestContextHolder. A developer could implement HandlerInterceptor which intercepts all incoming requests and sets contextual attributes on RequestContextHolder. These attributes are then accessible from anywhere in the code (via a static method) during the request lifetime.

Since in Reactive Web a request is not bound to a single processing thread, a simple use of ThreadLocal (what RequestContextHolder does) is not enough.
The Spring framework should offer a more sophisticated solution.

A simple but extremely intrusive workaround would be to pass in ServerWebExchange to all methods in all components - starting from controller endpoints down to all services.
But even if this is done, there is no good way to have a logger take attributes form the request (for the purpose of including trace/correlation ID) without implementing a wrapper around the logger class that receives an extra parameter.


Reference URL: https://stackoverflow.com/questions/43975761/how-to-get-the-context-of-the-current-request-in-spring-webflux

Issue Links:

19 votes, 34 watchers

Metadata

Metadata

Assignees

Labels

has: votes-jiraIssues migrated from JIRA with more than 10 votes at the time of importin: webIssues in web modules (web, webmvc, webflux, websocket)status: supersededAn issue that has been superseded by anothertype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions