Smallest Reactive RESTful service with Spring 5

Spring 5 is around the corner and with it comes a new reactive web framework called WebFlux and a new functional programming model.
Let’s use these features to write the smallest possible Hello world reactive RESTful service.

If you want to see how a more complete Reactive service looks like you can read the series Reactive RESTful service with Spring 5, Spring Boot 2 and MongoDB

public static void main(String[] args) {
	Undertow.builder().addHttpListener(8080, "localhost")
		.setHandler(new UndertowHttpHandlerAdapter(
			toHttpHandler(route(GET("/greetings"), request -> ok().body(fromObject("Hello World"))))))
		.build().start();
}
  1. route() method creates a RouterFunction that maps an HTTP verb to a HandlerFunction. Several mappings can be created by chaining calls to route() like this: route(…).and().route(…).and().route(…)
  2. toHttpHandler() passes the RouterFunction to a generic HTTP Handler
  3. The generic handler is then passed to an HTTP Handler specific to the runtime environment, here we use Undertow hence the specific class UndertowHttpHandlerAdapter
  4. Finally the Undertow server is created and started with build().start()

More on creating routes and using WefFlex in the reference documentation.

The service can be started with mvn spring-boot:run at the root directory of the project and tested in a web browser, with curl or any other client.

test-nano-rest

The full code of the project is available on github.

Advertisements