Spring Boot — Reactive Web

Apurv Sheth
3 min readMay 27, 2022

--

Introduction

In this article, we learned how to use Spring Data JDBC connectivity.

Today, we will learn to build an application that uses Spring Data R2DBC to store and retrieve data in a relational database using reactive database drivers.

Tools/Frameworks

IDE — IntelliJ Idea/Eclipse
Language — Java 8 or above
Framework — Spring boot, Project Reactor
Database — H2
Build Tool — Maven

Key Concept(s)

The heart of the project reactor is reactive-core. The main focus is on the Reactive Streams spec and targets Java 8 streams.

Project reactor introduced reactive types Flux & Mono that implement Publisher.

Flux — It represents an asynchronous sequence of zero or more objects

Mono —It represents asynchronous single or empty objects

The image given below very well describes the flux transformation very well. Please refer to the reference link at the end of the article for further readings.

Flux Transformation from projectreactor.io

Since we have gone through the basic concepts, let's jump on the implementation without having any delay.

Maven Dependency

Reactor — Maven Dependency

Configuration

First. let’s go through the configuration. As you have noticed, we have used the r2dbc configuration & the URL is prefixed with r2dbc but not with JDBC.

R2DBC Configuration

Implementation

Now, let’s have a look at the implementation. To have a reactive nature, we will implement ReactiveCrudRepository as shown below.

In our service class, we will return the Flux/Mono depending on our functionality.

Example — Flux/Mono Service

In our API resources also, we will return flux/mono as a response as shown below. However, the point to note down here is, that we need to set the “produces” media type as “MediaType.TEXT_EVENT_STREAM_VALUE”.

API/RestController with TEXT_EVENT_STREAM_VALUE media type

Huh, you might think, enough concepts & implementation but does it really work! Of course, it does, :) Let's go ahead & test.

Testing

I’m not sure if you have observed earlier, that I have kept a delay of 5 seconds before emitting the next objects so that we can verify that it's non-blocking asynchronous emitting of objects.

Testing

Yey, we have successfully implemented spring boot reactive web flux & verified the same.

If this post was helpful, please clap for few times or follow to show your support.

Git Repo

References

https://projectreactor.io/

--

--

Apurv Sheth

AWS Community Builder & Certified Solutions Architect | Cloud Enabler/Enthusiast | Spring Boot | Docker | Kubernetes | Microservices | Java/J2EE | Terraform