User5817351
User5817351

Reputation: 1007

How to pass thread local variable in Project Reactor

I started using project reactor. Does anyone know how can I pass thread local variables from one thread to another? I saw some methods on Hooks.java but could not figure out what is the recommended way of doing this. Can someone point me to some documentation or with a code snippet on how to do it. Thanks.

Upvotes: 2

Views: 7831

Answers (2)

Gooseman
Gooseman

Reputation: 2231

I have a working example in this github repository based on the spring-cloud-sleuth's implementation: https://github.com/gumartinm/JavaForFun/tree/master/SpringJava/WebReactive/spring-webreactive-reactor-context-enrich

The key classes are: ContextCoreSubscriber.java, SubscriberContext.java, ThreadContextEnrichmentAutoConfiguration.java and UsernameFilter.java

  • ContextCoreSubscriber.java:
    Enables you to fill the Mapped Diagnostic Context: MDC
  • SubscriberContext.java:
    Helper class for inserting data in the Reactor's Context.
  • ThreadContextEnrichmentAutoConfiguration.java:
    In charge of configuring the Reactor's Hooks: Hooks.onEachOperator
  • UsernameFilter.java:
    Example where we want to register the username information based on some HTTP header.

Upvotes: 8

Simon Baslé
Simon Baslé

Reputation: 28301

Reactor doesn't guarantee that the processing done by a Flux or Mono chain of operators will stick executing on a single thread. On the contrary, it performs work-stealing and lets the user switch execution context.

As such, using ThreadLocal is not very adapted to Reactor.

There is currently some work done in 3.1.0 towards providing an equivalent, at least for library authors that use Reactor, but nothing definite in place yet. Keep your eyes peeled for 3.1.0, that should be the main theme of that release (and will probably be the focus of the second upcoming milestone, M2).

Upvotes: 1

Related Questions