Create a WebFlux Handler
In the Spring Reactive approach, we use a handler to handle the request and create a response, as shown in the following example:
//src/main/java/hello/GreetingHandler.java
package hello;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Component
public class GreetingHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromValue("Hello, Spring!"));
}
}
This simple reactive class always returns “Hello, Spring!” It could return many other things, including a stream of items from a database, a stream of items that were generated by calculations, and so on. Note the reactive code: a Mono
object that holds a ServerResponse
body.
Create a Router
In this application, we use a router to handle the only route we expose (“/hello”), as shown in the following example:
//src/main/java/hello/GreetingRouter.java
package hello;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
@Configuration
public class GreetingRouter {
@Bean
public RouterFunction<ServerResponse> route(GreetingHandler greetingHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/hello").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), greetingHandler::hello);
}
}
The router listens for traffic on the /hello
path and returns the value provided by our reactive handler class.