DEV Community

Cover image for Getting started with Spring WebFlux and R2DBC in Spring Boot
Petros Stergioulas
Petros Stergioulas

Posted on • Updated on

Getting started with Spring WebFlux and R2DBC in Spring Boot

Introduction

In this short article I will try to introduce you to R2DBC using Spring Data R2DBC and in the world of reactive applications with Spring WebFlux.

What is R2DBC and why should you bother looking at it? First, R2DBC stands for Reactive Relational Database Connectivity. What does that mean? In simple words, R2DBC brings the possibility of non-blocking calls to our Relational Databases (SQL)!

Quoting https://r2dbc.io/, R2DBC is in a nutshell:

  • Reactive Streams - R2DBC is founded on Reactive Streams providing a fully reactive non-blocking API.
  • Relational Databases - R2DBC engages SQL databases with a reactive API, something not possible with the blocking nature of JDBC.
  • Scalable Solutions - Reactive Streams makes it possible to move from the classic one thread per connection approach to a more powerful, more scalable approach.
  • Open Specification - R2DBC is an open specification establishing a SPI that driver vendors can implement and clients can consume.

In this tutorial, we will build a simple REST API with Kotlin, Spring WebFlux and we will connect to our H2 Database using Spring Data R2DBC.

Getting Started

If you want to easily get started with a Springboot project I recommend always using the Spring Initializr.

The Second Best Place on the Internet @ Josh Long.

Gradle Configuration

First of all, we have to configure our build.gradle.kts and include the dependencies:

For the complete build.gradle.kts check here:
build.gradle.kts.

Application Configuration

Spring Boot comes with a handful of auto-configurations for Spring Data R2DBC out-of-the-box.
Below we are leveraging the power of Spring Boot to create a connection to the database:

Then we create a table called Employee and we populate it with some data:

While that may not seem really safe, in our application we do not have any problems, while the database will always be created on startup and destroyed on shutdown of the application.

REST API

Ok, so we created our database and we populated it with data, now what? Let's make use of it and create a REST API!

Below we have a simple domain model called Employee.

Then, let's create our repository, which will provide some queries out-of-the-box and we will also define one of our own.

Last but not least, let's create our endpoint:

Result

Let's execute our application with the command ./gradlew bootRun.

The application now runs on http://localhost:8080!! Congratulations!

Closing thoughts

Spring Data R2DBC is still on experimental stage. Although it is on the official release of Spring Boot 2.2.0, I would not recommend using it on production :).

I hope you now have a better understanding of R2DBC.

You can find the repository right here:




Resources

Top comments (0)