WebFlux: Reactive Programming With Spring, Part 3
The third part of the blog series contains an introduction to WebFlux – Spring's reactive web framework.
Join the DZone community and get the full member experience.Join For Free
This is the third part of my blog series on reactive programming, which will give an introduction to WebFlux — Spring’s reactive web framework.
1. An Introduction to Spring Webflux
The original web framework for Spring — Spring Web MVC — was built for the Servlet API and Servlet containers.
WebFlux was introduced as part of Spring Framework 5.0. Unlike Spring MVC, it does not require the Servlet API. It is fully asynchronous and non-blocking, implementing the Reactive Streams specification through the Reactor project (see my previous blog post).
WebFlux requires Reactor as a core dependency but it is also interoperable with other reactive libraries via Reactive Streams.
1.1 Programming Models
Spring WebFlux supports two different programming models: annotation-based and functional.
1.1.1 Annotated Controllers
If you have worked with Spring MVC, the annotation-based model will look quite familiar since it is using the same annotations from the Spring Web module as are being used with Spring MVC. The major difference being that the methods now return the reactive types Mono and Flux. See the following example of a RestController using the annotation-based model:
Some explanations about the functions used in the example:
mapfunction is used to transform the item emitted by a Mono by applying a synchronous function to it.
flatMapfunction is used to transform the item emitted by the Mono asynchronously, returning the value emitted by another Mono.
defaultIfEmptyfunction provides a default value if a Mono is completed without any data.
1.1.2 Functional Endpoints
The functional programming model is lambda-based and leaves the application in charge of the full request handling. It is based on the concepts of
HandlerFunctions are used to generate a response for a given request:
The RouterFunction is used to route the requests to the HandlerFunctions:
Continuing with the same student example we would get something like the following using the functional style.
And a StudentHandler:
Some explanations about the functions used in the example:
switchIfEmptyfunction has the same purpose as
defaultIfEmpty, but instead of providing a default value, it is used for providing an alternative Mono.
Comparing the two models we can see that:
- Using the functional variant requires some more code for things such as retrieving input parameters and parsing to the expected type.
- Not relying on annotations, but writing explicit code does offer some more flexibility and could be a better choice if we for example need to implement more complex routing.
1.2 Server Support
WebFlux runs on non-Servlet runtimes such as Netty and Undertow (non-blocking mode) as well as Servlet 3.1+ runtimes such as Tomcat and Jetty.
The Spring Boot WebFlux starter defaults to using Netty, but it is easy to switch by changing your Maven or Gradle dependencies.
For example, to switch to Tomcat, just exclude
spring-boot-starter-netty from the
spring-boot-starter-webflux dependency and add
Spring Boot provides auto-configuration for Spring WebFlux that works well for common cases. If you want full control of the WebFlux configuration, the
@EnableWebFlux annotation can be used (this annotation would also be needed in a plain Spring application to import the Spring WebFlux configuration).
If you want to keep the Spring Boot WebFlux config and just add some additional WebFlux configuration, you can add your own
@Configuration class of type
WebFluxConfigurer (but without
For details and examples, read the WebFlux config documentation.
2. Securing Your Endpoints
To get Spring Security WebFlux support, first, add the spring-boot-starter-security dependency to your project. Now you can enable it by adding the
@EnableWebFluxSecurity annotation to your Configuration class (available since Spring Security 5.0).
The following simplified example would add support for two users, one with a USER role and one with an ADMIN role, enforce HTTP basic authentication, and require the ADMIN role for any access to the path
It is also possible to secure a method rather than a path, by first adding the annotation
@EnableReactiveMethodSecurity to your config:
And then adding the
@PreAuthorize annotation to the methods to be secured. We might for example want our POST, PUT and DELETE methods only to be accessible by the ADMIN role. Then the PreAuthorize annotation could be applied to those methods, like:
Spring Security offers more support related to WebFlux applications, such as CSRF protection, OAuth2 integration, and reactive X.509 authentication. For more details, read the following section in the Spring Security documentation: Reactive Applications.
Spring WebFlux also includes a reactive, fully non-blocking web client. It has a functional, fluent API based on Reactor.
Let’s take a look at a (once again) simplified example, how the WebClient can be used to query our StudentController:
For testing your reactive web application, WebFlux offers the WebTestClient, which comes with a similar API as the WebClient.
Let’s have a look at how we can test our StudentController using the WebTestClient:
5. WebSockets and RSocket
With Spring 5, WebSockets also gets added reactive capabilities. To create a WebSocket server, you can create an implementation of the
WebSocketHandler interface, which holds the following method:
This method is invoked when a new WebSocket connection is established and allows handling of the session. It take a
WebSocketSession as input and returns
Mono<Void> to signal when application handling of the session is complete.
The WebSocketSession has methods defined for handling the inbound and outbound streams:
Spring WebFlux also provides a
WebSocketClient with implementations for Reactor Netty, Tomcat, Jetty, Undertow, and standard Java.
For more details, read the following chapter in Spring’s Web on Reactive Stack documentation: WebSockets
RSocket is a protocol that models Reactive Streams semantics over a network. It is a binary protocol for use on byte stream transports such as TCP, WebSockets, and Aeron. For an introduction to this topic, I recommend the following blog post that my colleague Pär has written: An introduction to RSocket.
And for more details on Spring Framework’s support for the RSocket protocol: RSocket.
6. To Summarize…
This blog post demonstrated how WebFlux can be used to build a reactive web application. The next and final blog post in this series will show how we can make our entire application stack fully non-blocking by also implementing non-blocking database communication — using R2DBC (Reactive Relational Database Connectivity)!
Published at DZone with permission of Anna Eriksson. See the original article here.
Opinions expressed by DZone contributors are their own.