Build Reactive Restful API Using Spring 5 (WebFlux), Springboot

1. Spring 5 WebFlux

Spring 5 includes a new reactive module called WebFlux. It builds on the reactive streams. (Key Spring Doc)

WebFlux support two programming models: one is traditional based@controller, the other is functional Java 8 lambda style routing and handling.  Here we will take a look at the second one.

In general, the second WebFlux model takes incoming http request, handed by the HandlerFunction , then http request body transforms to as Flux or Mono;

Flux and Mono come from the reactor (doc). A Flux object represents a reactive sequence of 0..N items, while a Monoobject represents a single-value-or-empty (0..1) result.

2. Code example
2.1 Create a handler:

public class UserHandler {

    public Mono getUser(ServerRequest request){
                String uuid = request.pathVariable("uuid");
                return ServerResponse
                        .body(BodyInserters.fromObject(new UserJson(uuid, "bob")));
            }catch (IllegalArgumentException i){
                return ServerResponse.badRequest()
2.2 Create a route:

public class UserRouter {

    public RouterFunction route(UserHandler userHandler){
        return RouterFunctions.route(RequestPredicates.GET("/users/{uuid}").

Source Code example Github

Author: aerodc

Software Engineer