Spring WebFlux is a reactive-stack web framework, part of Spring 5, fully non-blocking and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers
This guide will give you the steps to build a non-blocking web API with Spring WebFlux in a Spring Boot project
What you'll need
- JDK 8+ or OpenJDK 8+
- Maven 3+
Init project structure
You can create and init a new Spring Boot project by using Spring CLI or Spring Initializr. Learn more about using these tools at here
The final project structure as below
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── hellokoding
│ │ └── spring
│ │ ├── HelloApplication.java
│ │ ├── HelloHandler.java
│ │ └── HelloRouter.java
│ └── resources
│ ├── static
│ ├── templates
│ └── application.properties
└── pom.xml
Project dependencies
Add spring-boot-starter-webflux
into your project as a dependency on pom.xml or build.gradle file. The library versions can be omitted as it is resolved by the parent pom provided by Spring Boot
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
You can find the full pom.xml file as below
Define a reactive API handler
The handler method declaration is defined by HandlerFunction
, a functional interface in Spring, as below
package org.springframework.web.reactive.function.server;
import reactor.core.publisher.Mono;
@FunctionalInterface
public interface HandlerFunction<T extends ServerResponse> {
Mono<T> handle(ServerRequest request);
}
Define a reactive API router
Here we route GET requests for "/hello" to the hello
method in helloHandler
object
Define application bootstrap
Run and Test
You can run the application by typing the following command on the terminal console at the project root directory
$ mvn clean spring-boot:run
You would see this text in the console
o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
Access to http://localhost:8080/hello
on your web browser, the following response is expected
Hello, Spring WebFlux!
Conclusion
In this tutorial, we learned to build a reactive web API by using Spring WebFlux in a Spring Boot project. You can find the full source code on GitHub