Router Functions in Spring Reactive

Spring Reactive programming is an asynchronous and non-blocking paradigm for developing highly responsive applications. It enables developers to build applications that handle high-load traffic without compromising performance. Spring WebFlux, a part of the Spring Framework, supports reactive programming with non-blocking, backpressure-enabled types from the Reactor project. In this article, we will explain how Router Functions work with related examples. These Router Functions are part of the spring-webflux module.

Router Functions:

The Router Functions are an alternative to the annotated-based Spring MVC programming model. Instead of using annotations like @GetMapping, @PostMapping and we can define routes using functional program paradigms and this approach provides a more flexible and composable way to define routes. If you want to create a Router Function then first create a configuration class in that class and create a Router function by using RouterFunction is an interface that is used to represent a function that routes to a handler function.

Syntax:

@Configuration
public class Class_Name {

@Autowired
private Handler routerHandler;

@Bean
public RouterFunction<ServerResponse> route() {
return RouterFunctions
.route(RequestPredicates.GET("/"), routerHandler::handleHello);
}
}


Prerequisites:

  • Spring framework
  • Spring Reactive Programming
  • Publisher
  • Consumer
  • Event Handling
  • Router functionality

Implementation of Router Functions in Spring Reactive

For Implementation of Router Functions in Spring Reactive, here we created one simple spring reactive project after that we created one service class for defining the business logic after this we created one configuration class for creating router functions. Below, we provide the in detail explanation with examples for better understanding the concept.

Step 1: Create Project

Create a Spring Reactive project by using Spring Initializr and add the necessary dependencies.

Project Folder Structure:

After creating the project, the structure will be like below:


Step 2: Service Handler Class

Now, we created one Service Handler class by using @Service Spring Annotation and the Service class name is RouterHandler. After this We write required business logic.

Java
package com.router.app;

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import reactor.core.publisher.Mono;

@Service
public class RouterHandler {
    public Mono<ServerResponse> handleHello(ServerRequest request) {
        return ServerResponse.ok().bodyValue("Hello, World!");
    }

    public Mono<ServerResponse> handleEcho(ServerRequest request) {
        return request.bodyToMono(String.class)
                      .flatMap(body -> ServerResponse.ok().bodyValue("Echo: " + body));
    }
}


In the above class, we created two different methods namely handleHello and handleEcho. Here we use Mono publisher for creating API end points. And the ServerResponse is used for return the server response by using Mono publisher. The first method is GET HTTP request and the second method is POST HTTP request type.

  • handleHello():
    • This GET type of API endpoint method.
    • And It returns a Monotype of response.
  • handleEcho():
    • This method is a POST type of endpoint.
    • And It returns a String Type Mono publisher by using Server Response in the form of the body.


Step 3: Configuration Class

Once Business logic is completed, then we define the RouterFunction to create the API end point. We already explain what is RouterFunction in the above.

Java
package com.router.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 ParentRouter {
    
    @Autowired
    private RouterHandler routerHandler;
    
    @Bean
    public RouterFunction<ServerResponse> route() {
        return RouterFunctions
                .route(RequestPredicates.GET("/hello"), routerHandler::handleHello)
                .andRoute(RequestPredicates.POST("/echo"), routerHandler::handleEcho);
    }
}


In the above ParentRouter class, we define a Router Function by using the RouterFunction interface and this function returns a route function only. In the above example, we create two APIs endpoints.


Step 4: Run the Project

Now, run this Project as Spring Boo App. Once the project is successfully running and this project is by default running on Netty Server with default port number 8080.


Step 5: Test the API

Now Test the API endpoints here we use the Postman tool to test the Router functions API in the above example.

hello API endpoint:

http://localhost:8080/hello

Output:


echo End Point:

http://localhost:8080/echo

Output:



Contact Us