Spring WebFlux REST Application Integration with Spring Data R2DBC
Last Updated :
24 May, 2024
Spring WebFlux is the framework from the Spring ecosystem that supports reactive programming for building asynchronous and non-blocking web applications. Unlike the traditional Spring MVC, which can use the blocking I/O. WebFlux can be designed to handle large volumes of requests using fewer resources by leveraging reactive streams.
The main idea of integrating Spring WebFlux with Spring Data R2DBC is to create a responsive REST API that can interact with relational databases in a non-blocking way Spring Data Reactive Relational Database Connectivity (R2DBC) is a permissive specification for reactive programming and relational databases. It supports WebFlux by providing a responsive way of interacting with SQL databases.
Use of Spring WebFlux and R2DBC
- Scalability: It can handle more requests with fewer threads.
- Performance: It can improve the performance for I/O bound tasks.
- Modern Database Interaction: It can leverage the reactive streams for the database operations.
Implementation of Spring WebFlux REST Application Integration with Spring Data R2DBC
We will develop a simple CRUD application using the WebFlux and R2DBC.
Step 1: Create the New Spring Project
We can create the new spring project using spring initializer on creating the project and add the below dependencies into the project.
- Spring Reactive
- Spring Data R2DBC
- Lombok
- PostgreSQL Driver
- Spring DevTools
After doing the above step, the project structure will be like below.

Step 2: Configuring Application Properties
Open the application.properties file and put the below code for the server port and PostgreSQL database configuration to the project.
spring:
r2dbc:
url: r2dbc:postgresql://localhost:5432/webfluxr2dbcdb
username: postgres
password: mahesh
logging:
level:
org.springframework.r2dbc.core: DEBUG
Step 3: Database Schema
We can create the schema.sql file in the src/main/resources directory for creating the users table into the database.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL
);
Step 4: Create the User Entity
Go to src > org.example.springreactiver2dbc > model > User and put the below code.
Java
package org.example.springreactiver2dbc.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;
@Table("users")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@Id
private Long id;
private String name;
private String email;
}
Step 5: Create the UserRepository Class.
Go to src > org.example.springreactiver2dbc > repository > UserRepository and put the below code.
Java
package org.example.springreactiver2dbc.repository;
import org.example.springreactiver2dbc.model.User;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends ReactiveCrudRepository<User, Long> {
}
Step 6: Create the UserService Class.
Go to src > org.example.springreactiver2dbc > service > UserService and put the below code.
Java
package org.example.springreactiver2dbc.service;
import org.example.springreactiver2dbc.model.User;
import org.example.springreactiver2dbc.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Flux<User> getAllUsers() {
return userRepository.findAll();
}
public Mono<User> getUserById(Long id) {
return userRepository.findById(id);
}
public Mono<User> createUser(User user) {
return userRepository.save(user);
}
public Mono<User> updateUser(Long id, User user) {
return userRepository.findById(id)
.flatMap(existingUser -> {
existingUser.setName(user.getName());
existingUser.setEmail(user.getEmail());
return userRepository.save(existingUser);
});
}
public Mono<Void> deleteUser(Long id) {
return userRepository.deleteById(id);
}
}
Step 7: Create the UserController Class.
Go to src > org.example.springreactiver2dbc > controller > UserController and put the below code.
Java
package org.example.springreactiver2dbc.controller;
import org.example.springreactiver2dbc.model.User;
import org.example.springreactiver2dbc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public Flux<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public Mono<ResponseEntity<User>> getUserById(@PathVariable Long id) {
return userService.getUserById(id)
.map(user -> ResponseEntity.ok(user))
.defaultIfEmpty(ResponseEntity.notFound().build());
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Mono<User> createUser(@RequestBody User user) {
return userService.createUser(user);
}
@PutMapping("/{id}")
public Mono<ResponseEntity<User>> updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.updateUser(id, user)
.map(updatedUser -> ResponseEntity.ok(updatedUser))
.defaultIfEmpty(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public Mono<ResponseEntity<Void>> deleteUser(@PathVariable Long id) {
return userService.deleteUser(id)
.map(r -> ResponseEntity.ok().<Void>build())
.defaultIfEmpty(ResponseEntity.notFound().build());
}
}
Step 8: Main Class
Open the main class and add the @EnableR2dcRepositories annotation for activating the R2DBC functionalities of the Spring Application.
Java
package org.example.springreactiver2dbc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
@SpringBootApplication
@EnableR2dbcRepositories
public class SpringReactiveR2DbcApplication {
public static void main(String[] args) {
SpringApplication.run(SpringReactiveR2DbcApplication.class, args);
}
}
pom.xml:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>spring-reactive-R2DBC</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-reactive-R2DBC</name>
<description>spring-reactive-R2DBC</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>r2dbc-postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 9: Run the application
After completing the project, run the application and it will it start at port 8080.

Step 10: Testing the API Endpoints
Create the User:
POST http://localhost:8080/users

GET All the Users:
GET http ://localhost :8080/users

GET by the UserId:
GET http://localhost:8080/users/2

Update the User:
PUT http://localhost:8080/users/2

DELETE by UserId:
DELETE http://localhost:8080/users/2

User Table in PostgreSQL Database:

By following these steps, we can demonstrate simple CRUD application with Spring WebFlux integration with R2DBC.
Similar Reads
Spring WebFlux Application Integration with Reactive Messaging System Kafka Spring WebFlux is the framework for building reactive applications on the JVM. It is useful for reactive programming and makes it easier to build asynchronous, non-blocking and event-driven applications. Apache Kafka is a distributed streaming platform which allows us to publish and subscribe to str
5 min read
Creating REST APIs Using Spring WebFlux and MongoDB Spring Boot is the most popular Java framework for building stand-alone Java-based applications quickly and with minimal configuration. WebFlux is a responsive operating system provided by the Spring framework for running non-blocking, asynchronous, and event-driven applications. On the other hand,
10 min read
Containerize Spring WebFlux Application In todayâs Web development, containerization has become a dominant way of deploying and managing applications. The containers package application provides a consistent environment in the development and production phases. Docker is a popular tool for building, deploying, and running applications usi
3 min read
Security with Spring Security and Spring Webflux Spring WebFlux is a part of the Spring Framework that supports reactive programming, enabling non-blocking asynchronous request handling. When developing web applications with Spring WebFlux, securing the application is a crucial aspect to ensure unauthorized access is prevented. This article provid
3 min read
Spring Security Integration with Spring Boot Spring Security is a powerful and customizable authentication and access control framework for Java applications. It provides comprehensive security services for Java EE-based enterprise software applications. This article will integrate Spring Security with a Spring Boot application, covering confi
5 min read
Spring Cloud Gateway with Spring WebFlux Spring Cloud Gateway is the library that allows you to build API gateways on top of Spring WebFlux. It provides a simple and effective way to route requests, apply filters, and manage cross-cutting concerns reactively. This article will guide you through demonstrating how to set up Spring Cloud Gate
5 min read