Google Cloud SQL for PostgreSQL + Spring Boot + Spring WebFlux + R2DBC - Building Reactive REST CRUD APIs

In this section, we will learn how to use Spring Boot, Spring WebFlux, and R2DBC to create a reactive web service that interacts with Google Cloud SQL for PostgreSQL.

Reactive APIs are non-blocking and tend to be more efficient because they’re not tying up processing while waiting for stuff to happen. Reactive systems adopt asynchronous I/O. Reactive apps allow us to scale better if we are dealing with lots of streaming data. 

If we are going to build a reactive app, we need it to be reactive all the way down to your database. 

Spring WebFlux uses a library called Reactor for its reactive support. The Reactor is an implementation of the Reactive Streams specification. The Reactor Provides two main types called Flux and Mono. Both of these types implement the Publisher interface provided by Reactive Streams. Flux is used to represent a stream of 0..N elements and Mono is used to represent a stream of 0..1 element.

1.  A little bit of Background

Google Cloud SQL for PostgreSQL

Cloud SQL for PostgreSQL is a fully managed database service that helps you set up, maintain, manage, and administer your PostgreSQL relational databases on Google Cloud Platform.

Spring WebFlux

The original web framework included in the Spring Framework, Spring Web MVC, was purpose-built for the Servlet API and Servlet containers. The reactive-stack web framework, Spring WebFlux, was added later in version 5.0. It is fully non-blocking, supports Reactive Streams back pressure, and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers. 
More Info - click here!

Spring Boot

Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can "just run". 

2. Create a GCP Project

First, Sign into the Google console at

You can create a new project by first selecting the project dropdown in the top left and selecting "New Project".

Next, specify your GCP Project name and Project ID.

Then Click on the "CREATE" button.

Copy "Project ID" and keep it for future purposes.

3. Create a Cloud SQL for PostgreSQL instance.

From cloud console, search for "SQL" like below and click on "SQL" button.

Next, click on "CREATE INSTANCE" button,

Then, click on "Choose PostgreSQL" button,

Then, enable the Compute Engine API by click on "ENABLE API" button.

After that, enter "Instance Id", "Password", "Choose a configuration to start with", "Region" etc...

Note "Password" and keep it safely for future purposes.

Then click on "CREATE INSTANCE" button,

Next, copy "Connection name" and keep it for future purposes.

4. Create a Database.

Click on "CREATE DATABASE" button,

Enter "Database name" and then click on "CREATE" button.

Copy "Database name" and keep it for future purposes.

5. Enable SQL admin API

From cloud console, search for "sqladmin API" like below and click on "sqladmin API" button.

Next, click on "ENABLE" button,

6. Create a service account key

First choose "IAM & Admin" and then click on "Service accounts".

After that, click on "CREATE SERVICE ACCOUNT".

Then, enter service account details like "Service account name", and "Service account ID" and click on "CREATE AND CONTINUE".

Then, grant basic role Editor.

Finally click on "DONE" button.

Then, from "Actions" click on "Manage keys".

Then, click on "Create new key".

Then, choose "Key type" as JSON and click on "CREATE" button.

Service account keys in JSON format will be download. Keep the file safe for future purposes.

7. Creating a simple spring boot web application

First, open the Spring initializr 

Then, Provide the Group and Artifact name. We have provided Group name and Artifact spring-boot-webflux-gcp-sql-postgres-r2dbc-example. Here I selected the Maven project - language Java 17 - Spring Boot 3.0.4 and add Spring Reactive Weband GCP Support.

Then, click on the Generate button. When we click on the Generate button, it starts packing the project in a .zip(spring-boot-webflux-gcp-sql-postgres-r2dbc-example) file and downloads the project. Then, Extract the Zip file. 

Then, import the project on your favourite IDE.

Final Project directory:

In the pom.xml, add CloudSQL Starter for PostgreSQL R2DBC:

<!-- Add CloudSQL Starter for PostgreSQL R2DBC -->

    Complete pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns=""
    <relativePath/> <!-- lookup parent from repository -->
    <description>Demo project for Spring Boot</description>




    Add the following configuration to file:

    # Uncomment if root password is specified

    # Leave empty to use the default username (`postgres`), uncomment and fill out if you specified a user
    # spring.r2dbc.username=

    Specify database name, instance name, project id, credential's location, and datasource password.

    Note: In this example, we placed service account key JSON file in resources folder (Not recommended in production environment).

    More secure way is place JSON in somewhere in server or docker image, then create environment variable "GOOGLE_APPLICATION_CREDENTIALS" and give the location to your JSON FILE.

    If your application is running on Google App Engine or Google Compute Engine, in most cases you should omit the "" property and instead, let Spring Cloud GCP Core Starter find the correct credentials for those environments.


    id serial primary key,
    name VARCHAR(40) not null,
    email VARCHAR(40) not null



    import io.r2dbc.spi.ConnectionFactory;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer;
    import org.springframework.r2dbc.connection.init.ResourceDatabasePopulator;

    public class DBConfig {

    ConnectionFactoryInitializer initializer(
    ConnectionFactory connectionFactory) {

    ConnectionFactoryInitializer initializer =
    new ConnectionFactoryInitializer();
    new ResourceDatabasePopulator(
    new ClassPathResource("schema.sql")));
    return initializer;

    Spring Data R2dbc does not maintain the database schemas, so you have to do it yourself. Spring Data R2dbc provides a ConnectionFactoryInitializer to allow you execute sql scripts on database when it is connected.

    Create model



    public class Student {

    private Long id;
    private String name;
    private String email;

    public Student() {

    public Student(Long id, String name, String email) { = id; = name; = email;

    public Long getId() {
    return id;

    public void setId(Long id) { = id;

    public String getName() {
    return name;

    public void setName(String name) { = name;

    public String getEmail() {
    return email;

    public void setEmail(String email) { = email;

    Create Reactive Crud Repository [] 



    public interface StudentRepository
    extends ReactiveCrudRepository<Student, Long> {

    ReactiveCrudRepositoryInterface for generic CRUD operations on a repository for a specific type. This repository follows reactive paradigms and uses Project Reactor types which are built on top of Reactive Streams.

    Create Student Controller


    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    import reactor.core.publisher.Flux;
    import reactor.core.publisher.Mono;

    public class StudentController {

    private StudentRepository studentRepository;

    Flux<Student> getAll() {

    return studentRepository.findAll();

    Mono<Student> getStudent(@PathVariable("id") Long id) {

    return studentRepository.findById(id);

    Mono<Student> addStudent(@RequestBody Student student) {


    private Mono<Student> updateStudent(@PathVariable("id") Long id,
    @RequestBody Student student) {

    return studentRepository.findById(id).flatMap(user1 -> {

    Mono<Void> deleteById(@PathVariable("id") Long id) {

    return studentRepository.findById(id).flatMap(p ->
    • Spring @RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON response.
    • @RequestMapping is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods.
    • We can use the @Autowired to mark a dependency which Spring is going to resolve and inject.
    • @GetMapping annotation for mapping HTTP GET requests onto specific handler methods.
    • @PostMapping annotation for mapping HTTP POST requests onto specific handler methods.
    • @PutMapping annotation for mapping HTTP PUT requests onto specific handler methods.
    • @DeleteMapping annotation for mapping HTTP DELETE requests onto specific handler methods.
    • @RequestBody annotation is used to indicating a method parameter should be bind to the body of the HTTP request. Internally, this annotation uses HTTP Message converters to convert the body of HTTP requests to domain objects.
    • @PathVariable annotation used on a method argument to bind it to the value of a URI template variable.
    • Spring WebFlux uses a library called Reactor for its reactive support. The Reactor is an implementation of the Reactive Streams specification. The Reactor Provides two main types called Flux and Mono. Both of these types implement the Publisher interface provided by Reactive Streams. Flux is used to represent a stream of 0..N elements and Mono is used to represent a stream of 0..1 element.

    Run the application -


    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    public class Application {

    public static void main(String[] args) {, args);


    Application is the entry point that sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.

    Step1: Download or clone the source code from GitHub to a local machine - Click here!

    Step 2: mvn clean install

    Step 3: Run the Spring Boot application - mvn spring-boot:run


    Run this Spring boot application from 

    • IntelliJ IDEA IDE by right click - Run 'Application.main()' 
    • Eclipse/STS - You can right click the project or the file and run as java application or Spring boot application.

    Add Student:

    Update Student:

    Fetch all Student:

    Get Student by Id:

    Delete Student:

    More Spring|GCP Examples - click here!

    Popular posts from this blog

    Learn Java 8 streams with an example - print odd/even numbers from Array and List

    Spring Boot + Mockito simple application with 100% code coverage

    Registration and Login with Spring Boot + Spring Security + Thymeleaf

    Spring boot video streaming example-HTML5

    Java Stream API - How to convert List of objects to another List of objects using Java streams?

    Java, Spring Boot Mini Project - Library Management System - Download

    ReactJS, Spring Boot JWT Authentication Example

    Custom Exception Handling in Quarkus REST API

    Spring Boot + OpenCSV Export Data to CSV Example

    Spring Webflux File Download Example