Spring Data and R2DBC by Example

R2DBC is a project that enables us to develop reactive programs API with relational databases, as we can do with databases that natively offer reactive drivers, like for example, Mongo or Cassandra.

Spring Data R2DBC is an abstraction of Spring to use repositories that support R2DBC and allows us a functional approach to interact with a relational database.

Streaming Live Updates From a Reactive Spring Data Repository

Here's an example implementation of streaming updates from a database to other components

This post details a naive implementation of streaming updates from a database to any other components that are interested in that data. More precisely, we look at how to alter a Spring Data R2DBC repository to emit events to relevant subscribers.

You may also like: Reactive Streams With Spring Data and MongoDB

A little bit of background knowledge of R2DBC and Spring will be helpful for this post. My previous writings: Asynchronous RDBMS access with Spring Data R2DBC and Spring Data R2DBC for Microsoft SQL Server — these should help in that regard.

Asynchronous RDBMS Access With Spring Data R2DBC

Not too long ago, a reactive variant of the JDBC driver was released, known as R2DBC. It allows data to be streamed asynchronously to any endpoints that have subscribed to it. Using a reactive driver like R2DBC together with Spring WebFlux allows you to write a full application that handles the receiving and sending of data asynchronously. In this post, we will focus on the database and on connecting to the database and then finally saving and retrieving data. To do this, we will be using Spring Data. As with all Spring Data modules, it provides us with out-of-the-box configuration, decreasing the amount of boilerplate code that we need to write to get our application setup. On top of that, it provides a layer upon the database driver that makes doing the simple tasks easier and the more difficult tasks a little less painful.

For the content of this post, I am making use of a Postgres database. At the time of writing only Postgres, H2 and Microsoft SQL Server have their own implementations of R2DBC drivers.