Senior
How to access a blocking data source (e.g., database) in a reactive pipeline?
sobes.tech AI
Answer from AI
In a reactive pipeline (for example, using Project Reactor or RxJava), blocking data sources such as databases should be wrapped in non-blocking calls to avoid blocking the reactive execution thread.
Typically, this is done using:
- A Scheduler with a dedicated thread pool for blocking operations (for example,
Schedulers.boundedElastic()in Reactor). - The call to the blocking method is executed within
subscribeOnorpublishOnwith such a Scheduler.
Example in Reactor:
Mono.fromCallable(() -> blockingDatabaseCall())
.subscribeOn(Schedulers.boundedElastic())
.map(result -> process(result))
.subscribe();
Thus, the blocking call is executed in a separate thread, not blocking the main reactive thread, and the result is asynchronously passed further down the pipeline.