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:

@Component
public class UserHandler {

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

@Configuration
public class UserRouter {

    @Bean
    public RouterFunction route(UserHandler userHandler){
        return RouterFunctions.route(RequestPredicates.GET("/users/{uuid}").
                and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
                userHandler::getUser);
    }
}

Source Code example Github

Author: aerodc

Software Engineer