Spring 5 has the new module WebFlux to create reactive web applications. Spring WebFlux supports two programming models: traditional annotation-based programming model and functional programming model. In this post, we’ll going to scratch the surface of the new functional programming model. This post assumes that you already know concepts like Flux and Mono in Reactor.
We’ll use a calculator service as the example. This service supports operations like add, subtract, divide and multiply with two operands. The parameter operator specifies the operation to call, while parameters v1 and v2 specify the two operands. For example, the url /calculator?operator=add&v1=1&v2=2 invokes the add operation with values 1 and 2.
The easiest way to create a WebFlux project is using Spring Initializr. We create a Maven-based Java project with Spring Boot 2.0.0-M5 and add Reactive Web as the dependency.
Handler functions are responsible for handling incoming HTTP requests. Each handler function takes a ServerRequest and returns a Mono<ServerResponse>. Multiple handler functions for the same service are typically organized in the same class.
In the CalculatorHandler listed below, we have different methods add, subtract, multiply and divide to handle different requests. These methods use calculate to parse the request and calculate the result.
Router functions are responsible for routing the incoming HTTP requests to the correct handler function. Each router function takes a ServerRequest, and returns a Mono<HandlerFunction>.
In the bean of type RouterFunction created by routerFunction, we only match the request path /calculator. We extract the parameter operator from the request and use reflections to find the correct handler function in CalculatorHandler to handle the request. We can see that Reactor makes the error handling very easy to implement and understand.