Transforming a synchronous repository into reactive

Although Spring Data provides reactive connectors for popular NoSQL databases, a reactive application sometimes needs to query a database that does not have reactive connectivity. Wrapping any blocking communication into a reactive API is possible. However, all blocking communication should happen on an appropriate thread pool. If not, we may block the event loop of the application and stop it entirely. Note, a small thread pool (with a bounded queue) is likely to be exhausted at some point. A full queue turns into blocking mode at some point and the whole point of making it non-blocking is gone. Such solutions are not as efficient as their entirely reactive counterparts. However, the approach with a dedicated thread pool for blocking requests is often acceptable in a reactive application.

Let's assume that we have to implement a reactive microservice that issues requests to a relational database from time to time. That database has a JDBC driver but does not have any asynchronous or reactive drivers. In this case, the only option would be to build a reactive adapter that hides blocking requests behind a reactive API.

As was previously stated, all blocking requests should happen on a dedicated scheduler. The underlying thread pool of the scheduler defines the level of parallelism for blocking actions. For example, when running blocking actions on Schedulers.elastic(), the amount of concurrent requests is not limited because the elastic scheduler does not bind the maximum number of created thread pools. At the same time, Scheduler.newParallel("jdbc", 10) defines the number of pooled workers, so no more than 10 concurrent requests will happen simultaneously. This approach works well when a communication with the database happens through the connection pool of a fixed size. In most cases, it makes little sense to set the size of the thread pool bigger than the size of the connection pool. For example, with a scheduler that operates over an unlimited thread pool, when the connection pool is exhausted, a new task and its running thread will be blocked not by the network communication but at the stage of connection retrieval from the connection pool.

When choosing the appropriate blocking API, there are a few options. Each option has its pros and cons. Here, we are going to cover the rxjava2-jdbc library and see how to wrap a pre-existing blocking repository.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.68.18