Reactive web using annotation with Spring WebFlux

As I said in my previous post, we can develop Reactive web applications using @RestController or @Controller annotations in Spring MVC using Spring WebFlux. How is it in detail? We will find out in this tutorial.

First, I will create a Spring Boot project with Reactive Web support using Spring Initializr Web http://start.spring.io/. Note that, only Spring Boot 2.x onwards supports Spring framework version 5.x.

My project is as follows:

Reactive web using annotation with Spring WebFlux

If you do not know how to create a Spring Boot project with Spring Initializr Web, please refer to this tutorial.

In this example, I will create an application that provides a list of students with data added every second. When a user requests to our application, whenever a new student is added, the student’s information is published to the user.

To implement this application, we need to do the following:

The first is: to create a Student object containing student information.

For simplicity, I will create a Student class with just a name attribute like this:

Next, I will create an object that can add a new student every second.

This object named StudentService is declared with the @Service annotation so that Spring Boot can automatically declare it in the Spring container.

In this object, we define an all() method. This method will use the RandomStringGenerator object from the Apache Commons Text library:

to generate a random name of the student:

Here, I will use the Flux object to generate a new student after a second and then return to the new student’s Flux object.

The entire code of the StudentService class is as follows:

The last step, we need to do, is: to define a request URL that the user can request.

I will define StudentController with the declaration using @RestController annotation.

In this controller, I define a request URL as “/students” and when the user requests it, I will use the StudentService object to find all the students added.

Note that, using annotation to build Reactive web applications is very similar to the Spring MVC, except the input or return type is different, we will use Reactor objects such as Mono or Flux.

Another thing to keep in mind that is: we are using produces with the value “text/event-stream”. This is an attribute, if you know the concept of Server-Send Event, help us can send updating content from the server to the client. The new student’s information is pushed down to the user whenever it is added.

That is it, let’s try running it.

You will see a new student added in a second and returned to the user as follows:

Reactive web using annotation with Spring WebFlux

Add Comment