How to start with Spring web-flux

Reading Time: 4 minutes

Spring Boot provides very good support for building RESTful Web Services for enterprise applications. This blog will explain building RESTful web services using Spring Boot in detail with a pinch of reactive programming using web flux. I will mostly be walking through the code snippets which we can use to quickly start with the web flux without having to dive deep. It is like a code-first approach.

Start with Build

If you are using Maven, use the following code to add the below dependency in your pom.xml file −

<?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>2.6.9</version>

		<relativePath/> <!-- lookup parent from repository -->

	</parent>

	<groupId>com.webflux</groupId>

	<artifactId>demo-webflux</artifactId>

	<version>0.0.1-SNAPSHOT</version>

	<name>demo-webflux</name>

	<description>Demo project for Spring Boot</description>

	<properties>

		<java.version>11</java.version>

	</properties>

	<dependencies>

		<dependency>

			<groupId>org.springframework.boot</groupId>

			<artifactId>spring-boot-starter-web</artifactId>

		</dependency>

		<dependency>

			<groupId>org.springframework.boot</groupId>

			<artifactId>spring-boot-starter-webflux</artifactId>

		</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>

		<dependency>

			<groupId>org.springframework.boot</groupId>

			<artifactId>spring-boot-starter-data-
mongodb</artifactId>

		</dependency>

		<dependency>

			<groupId>org.springframework.boot</groupId>

			<artifactId>spring-boot-starter-data-mongodb-
reactive</artifactId>

		</dependency>

	</dependencies>

	<build>

		<plugins>

			<plugin>

				<groupId>org.springframework.boot</groupId>


				<artifactId>spring-boot-maven-
plugin</artifactId>

			</plugin>

		</plugins>

	</build>

</project>

Code Implementation

REST CONTROLLER
We use the @RestController annotation to define the RESTful web services. It serves JSON, and custom responses.

@RestController

public class AnimalController {

}


The default HTTP request method is GET. This method does not require any Request Body. The request URI is /animalByName and it will return the value stored.

@GetMapping("/animalByName")

    public ResponseEntity<Flux<Animal>> findAnimalByName(){

        return new ResponseEntity<Flux<Animal>>

(animalService.findAnimalByName(), new HttpHeaders() ,HttpStatus.OK);

    }


The HTTP(Hypertext transfer protocol) POST request is used to create a resource. This method contains the Request Body. The request URI is /add, and it will return the value after adding a new animal name into the database.

    @PostMapping("/add")

    public ResponseEntity<Mono<Animal>> saveDataIntoDatabase(@RequestBody 

Animal animal){

        return new ResponseEntity<Mono<Animal>>

(animalService.saveDataIntoDatabase(animal) , new HttpHeaders() , 

HttpStatus.OK);

    }
    

Mono and Flux

Spring Webflux uses Project Reactor as the reactive library. Spring WebFlux heavily uses 2 publishers:

Mono: Returns zero or one part.
Flux: Returns 0…N components.
The reactor may be a Reactive Streams library and, therefore, all of its operators support non-blocking back-pressure. Reactor features a sturdy specialization in server-side Java. WebFlux needs Reactor as a core dependency however it’s practical with different reactive libraries via Reactive Streams.

What is Mono? Why do we use Mono?
Mono may be a Reactive Streams Publisher with basic operators that complete with success.
Let’s explore some features of Flux/Mono that facilitate to filter, transforming, and mixing of the Publisher stream
Filter the supply against the given predicate victimization the filter technique.

What is Flux? Why do we use Flux?
Flux could be a Reactive Stream Publisher with basic operators that emit zero to N components and then complete (successfully or with associate error).
The subscribe technique is employed to subscribe a client to the Flux that may consume all the weather within the sequence, similar to a client that may handle errors. you’ll concatenate emissions of this Flux with the provided Publisher exploitation of the concatWith technique. On invoking the error technique, Flux is formed that terminates with the desired error instantly when being signed.

Now we are going to create our main application classwebfluxexample.java

package com.knoldus.webfluxexample;


@EnableMongoRepositories

@EnableReactiveMongoRepositories

@SpringBootApplication

public class SpringWebfluxExampleApplication {


	public static void main(String[] args) {

		SpringApplication.run(SpringWebfluxExampleApplication.class, 

args);

	}

}

After the main application class, we will make the Controller class – animalcontroller.java

package com.knoldus.webfluxexample.controller;

@RestController

@RequestMapping("/animal")

public class AnimalController {

	@Autowired

    private final AnimalService animalService;

    public AnimalController(AnimalService animalService){

        this.animalService= animalService;

    }

}

After the controller class, we have to store our data so to store our data we will make an entity class – animal.java
In this class, we will define what data/value we want to store in our database

package com.knoldus.webfluxexample.entity;

@Document(collection = "Animal")

public class Animal {

@Id

private int id;

private String name;

private String address;

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getAddress() {

        return address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

    @Override

    public String toString() {

        return "Animal{" +

                "id=" + id +

                ", name='" + name + '\'' +

                ", address='" + address + '\'' +

                '}';

    }
}

Application Output

Let’s know how we will run our application
You can create an executable JAR file, and run the spring boot application by using the below Maven or Gradle commands as shown −

mvn clean install

After you get “BUILD SUCCESS”, you can find the JAR file under the target directory.

gradle clean build

After you get “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.

You can run the JAR file by using the command shown below −

java –jar

This will start the application on the Tomcat port 8089 as shown below −

Postman Collections

Now hit the URL shown below in the POSTMAN application and see the output.

POST API URL is: http://localhost:8089/animal/add

Now hit the URL shown below in the POSTMAN application and see the output.

GET API URL is: http://localhost:8080/animal/animalByName

Here I have attached the GitHub file which you will find here

Reference:

https://www.tutorialspoint.com/spring_boot_h2/index.htm
https://www.javaguides.net/2019/07/spring-boot-save-findbyid-findall.html

Written by 

Hey, I am a software consultant at Knoldus working on Java and Functional Programming.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading