Functional web framework

Building on top of the reactive features, Spring 5 also provides a functional web framework.

A functional web framework provides features to define endpoints using functional programming style. A simple hello world example is shown here:

    RouterFunction<String> route =
route(GET("/hello-world"),
request -> Response.ok().body(fromObject("Hello World")));

A functional web framework can also be used to define more complex routes, as shown in the following example:

    RouterFunction<?> route = route(GET("/todos/{id}"),
request -> {
Mono<Todo> todo = Mono.justOrEmpty(request.pathVariable("id"))
.map(Integer::valueOf)
.then(repository::getTodo);
return Response.ok().body(fromPublisher(todo, Todo.class));
})
.and(route(GET("/todos"),
request -> {
Flux<Todo> people = repository.allTodos();
return Response.ok().body(fromPublisher(people, Todo.class));
}))
.and(route(POST("/todos"),
request -> {
Mono<Todo> todo = request.body(toMono(Todo.class));
return Response.ok().build(repository.saveTodo(todo));
}));

A couple of important things to note are as follows:

  • RouterFunction evaluates the matching condition to route requests to the appropriate handler function
  • We are defining three endpoints, two GETs, and one POST, and mapping them to different handler functions

We will discuss Mono and Flux in more detail in Chapter 11, Reactive Programming.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset