Spring Boot Functional Reactive Programming Example


This tutorial will show you an example on Spring Boot Functional Reactive Programming (FRP). We will use both Gradle and Maven build tools to build the application.

Related Posts:

What are Reactive and Functional Reactive Programming?

Reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change.

In other words, Reactive Programming is a style of micro-architecture involving intelligent routing and consumption of events, all combining to change behaviour.

Simply to say, it is about non-blocking applications that are asynchronous and event-driven and require a small number of threads to scale vertically (i.e. within the JVM) rather than horizontally (i.e. through clustering).

Functional Reactive Programming (FRP) is a programming paradigm for reactive programming (asynchronous dataflow programming) using the building blocks of functional programming.

Use Cases Of Reactive Programming?

1. External service calls backend services and most of the backend services are RESTful APIs and they operate on http protocol. So the underlying protocol is blocking and synchronous.

Let’s say implementations of such services often involve calling of other services and then more services depending on the result of the subsequent service calls.

In such situations with so much IO going on, you need to wait for one call to complete before you send next request and your client may get “disconnected/timed out” for some reasons before you managed to assemble the reply for your client.

FRP offers the promise of “composability” of the logic to optimize the complex orchestrations of dependencies between service calls. So it becomes easier to write for the developer of the calling service.

2. Highly concurrent message consumers in message processing system are common enterprise use cases.

When you have to process millions of messages per second and performance matters, then you should pay attention to use Reactive patterns. Reactive patterns fit naturally with faster message processing since an event gets easily translated into a message.

3. As long as developers accept extra layer of abstraction, they can easily forget about the code that they are calling is synchronous or asynchronous. Since it costs precious brain cells to deal with asynchronous programming. Reactive Programming is not the only the solution but FRP tools are also useful to this issue.

Reactive Programming in Java

Java itself does not support Reactive Programming until version 9. However, Java being the powerhouse of enterprise application development, there are a lot of Reactive libraries that provide the Reactive programming on top of JDK. Such libraries are Reactive Streams, RxJava, Reactor, Spring Framework 5.0, RatPack  or may be more.

What is driving to the rise of Reactive programming?

Well, it’s not all just about the technology. The driver is efficient resource utilization, or in other words, spending less money on servers and data centres.

The promise of Reactive is that you can do more with less, specifically you can process higher loads with fewer threads. This is where the intersection of Reactive and non-blocking, asynchronous I/O comes to the foreground.

For the right problem, the effects are elegant. For the wrong problem, the effects might go into reverse (you actually make things worse).

Reactive Programming using Spring Framework

The Spring framework uses Reactor internally for its own reactive support. Reactor is a Reactive Streams implementation that further extends the basic Reactive Streams Publisher contract with the Flux and Mono composable API types to provide declarative operations on data sequences of 0..N and 0..1.

Spring Framework 5 includes a new spring-webflux module. The module contains support for reactive HTTP and WebSocket clients as well as for reactive server web applications including REST, HTML browser, and WebSocket style interactions.

On the server-side WebFlux supports 2 distinct programming models:

  • Annotation-based with @Controller and the other annotations supported also with Spring MVC
  • Functional, Java 8 lambda style routing and handling

Both programming models are executed on the same reactive foundation that adapts non-blocking HTTP runtimes to the Reactive Streams API. The diagram below shows the server-side stack including traditional, Servlet-based Spring MVC on the left from the spring-webmvc module and also the reactive stack on the right from the spring-webflux module.

spring boot reactive

We will see here Functional, Java 8 lambda style routing and handling Reactive Programming example. If you want to implement annotation based programming model then you can check here at WebFlux Framework.

We will also use here Spring Boot Framework to create the example. The example will perform CRUD(Create, Read, Update and Delete) operations using REST APIs.

Enough talking about Reactive Programming… Now let’s move on to the Spring Boot Functional Reactive programming example.


Eclipse 2019-12, At least Java 8, Spring Boot Webflux 2.2.6, Gradle 6.1.1, Maven 3.6.3

Setup Project

Create a gradle based Spring Boot project in Eclipse. Here in this example I am using JDK 12 and Eclipse.

The name of the project is spring-boot-reactive.

Make sure to update the your build.gradle script as shown below:

buildscript {
    ext {
        springBootVersion = '2.2.6.RELEASE'
    repositories {
    dependencies {

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

sourceCompatibility = 12
targetCompatibility = 12

repositories {

dependencies {

Once you update the build script, try to build the blank project. If you face any build issue related to main class then create a class with main method you should be fine to build the blank project.

If you are using Maven as a build tool then you can use below pom.xml file for your project.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">





					<source>at least 8</source>
					<target>at least 8</target>

Create Model

Create below model class that simply has few attributes.

package com.roytuts.model;

public class WebSite {

	private Integer id;
	private String url;
	private String title;

	//getters and setters


Create Repository

Create below repository class that is a source of data on which you want to do apply some business or processing logic.

For this example, we will use this class as a source of data. Ideally your source of data should be any database or any external service.

Here I have initially provided my two websites in the repository that will help you to test the reactive application.

package com.roytuts.repository;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.roytuts.model.WebSite;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class WebSiteRepository {

	private static final Map<Integer, WebSite> WEBSITES = new HashMap<>();
	static {
		WebSite webSite1 = new WebSite();
		webSite1.setTitle("Roy Tutorials");
		WEBSITES.put(1, webSite1);

		WebSite webSite2 = new WebSite();
		webSite2.setTitle("JEE Tutorials");
		WEBSITES.put(2, webSite2);
	private static int ID_COUNTER = 3;

	public Flux<WebSite> findAll() {
		return Flux.fromIterable(WEBSITES.values());

	public Mono<WebSite> findById(Integer id) {
		return Mono.just(WEBSITES.get(id));

	public Mono<Void> delete(Integer id) {
		return Mono.empty();

	public Mono<Void> add(Mono<WebSite> webSite) {
		return webSite.doOnNext(wb -> {
			Integer id = ID_COUNTER++;
			WEBSITES.put(id, wb);

	public Mono<Void> update(Mono<WebSite> webSite) {
		return webSite.doOnNext(wb -> {
			WEBSITES.put(wb.getId(), wb);


In the above example you can find details here on Flux and Mono.

Now we will see two important functions of Reactive Streams – Handler Function and Router Function.

Creating Handler Functions

Writing handler functions as lambdas’ is convenient, but perhaps lacks in readability and becomes less maintainable when dealing with multiple functions. Therefore, it is recommended to group related handler functions into a handler or controller class.

For example, here is a class that exposes a reactive WebSite repository:

package com.roytuts.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.roytuts.model.WebSite;
import com.roytuts.repository.WebSiteRepository;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class WebSiteHandler {

	private WebSiteRepository webSiteRepository;

	public Mono<ServerResponse> getAllWebSites(ServerRequest serverRequest) {
		Flux<WebSite> webSites = webSiteRepository.findAll();
		return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(webSites, WebSite.class);

	public Mono<ServerResponse> addWebSite(ServerRequest serverRequest) {
		Mono<WebSite> webSite = serverRequest.bodyToMono(WebSite.class);
		return ServerResponse.ok().build(webSiteRepository.add(webSite));

	public Mono<ServerResponse> updateWebSite(ServerRequest serverRequest) {
		Mono<WebSite> webSite = serverRequest.bodyToMono(WebSite.class);
		return ServerResponse.ok().build(webSiteRepository.update(webSite));

	public Mono<ServerResponse> deleteWebSite(ServerRequest serverRequest) {
		Integer webSiteId = Integer.valueOf(serverRequest.pathVariable("id"));
		return ServerResponse.ok().build(Mono.empty());

	public Mono<ServerResponse> getWebSite(ServerRequest serverRequest) {
		Integer webSiteId = Integer.valueOf(serverRequest.pathVariable("id"));
		Mono<ServerResponse> notFound = ServerResponse.notFound().build();
		Mono<WebSite> webSiteMono = webSiteRepository.findById(webSiteId);
		return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(webSiteMono, WebSite.class)


In the above class, incoming HTTP requests are handled by a HandlerFunction, which is essentially a function that takes a ServerRequest and returns a Mono<ServerResponse>.

ServerRequest and ServerResponse are immutable interfaces and both are fully reactive by building on top of Reactor: the request expose the body as Flux or Mono; the response accepts any Reactive Streams Publisher as body.

ServerRequest gives access to various HTTP request elements: the method, URI, query parameters, and — through the separate ServerRequest.Headers interface — the headers.

Similarly, ServerResponse provides access to the HTTP response. Since it is immutable, you create a ServerResponse with a builder. The builder allows you to set the response status, add response headers, and provide a body.

getAllWebSites() is a handler function that returns all WebSite objects found in the repository as JSON.

getWebSite() is a handler function that returns single WebSite object for a given id found in the repository as JSON.

addWebSite() and updateWebSite() are handler functions that store a new WebSite and update existing WebSite contained in the request body, respectively.

Note that WebSiteRepository.add(Mono<WebSite>) returns Mono<Void>: an empty Mono that emits a completion signal when the website has been read from the request and stored. So we use the build(Publisher<Void>) method to send a response when that completion signal is received, i.e. when the WebSite has been added.

getWebSite() is a handler function that returns a single website, identified via the path variable id. We retrieve that WebSite via the repository, and create a JSON response if it is found. If it is not found, we use switchIfEmpty(Mono<T>) to return a 404 Not Found response.

Creating Router Functions

Incoming requests are routed to handler functions with a RouterFunction, which is a function that takes a ServerRequest, and returns a Mono<HandlerFunction>. If a request matches a particular route, a handler function is returned; otherwise it returns an empty Mono.

Given the WebSiteHandler we showed above, we can now define a router function that routes to the respective handler functions.

We use method-references to refer to the handler functions:

package com.roytuts.router;

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;

import com.roytuts.handler.WebSiteHandler;

public class WebSiteRouter {

	public RouterFunction<ServerResponse> route(WebSiteHandler webSiteHandler) {
		RouterFunction<ServerResponse> webSiteRoute = RouterFunctions
						.and(RequestPredicates.accept(MediaType.APPLICATION_JSON)), webSiteHandler::getWebSite)
		return webSiteRoute;


Besides router functions, you can also compose request predicates, by calling RequestPredicate.and(RequestPredicate) or RequestPredicate.or(RequestPredicate).

These work as expected: for and the resulting predicate matches if both given predicates match; or matches if either predicate does. Most of the predicates found in RequestPredicates are compositions.

Notice how we have used lambda expression to functional interfaces in the above Router Functions, that’s why the title name is given as Spring Boot Functional Reactive Programming example.

Creating main class

We need to deploy the application into a server. So creating below main class will simply treated as a standalone application. Along the way, you use Reactive Spring’s support for embedding the Netty server as the HTTP runtime, instead of deploying to an external instance.

package com.roytuts.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.roytuts")
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);


Reactive programming is just about finding ways to stream data and events through a pipeline, rather than dealing discreetly with each event, change, or response. You can develop your application not in a set of interconnected callback functions and event listeners, but a logical flow from events to actions, which themselves flow into other things.

Creating Cors filter to allow access to server from your client(s)

This is required in order to gain access to server REST services. You are easily allowed to get access to http GET method without any issue but for other methods you need below filter class otherwise you will be stuck in preflight request.

package com.roytuts.filter;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;

import reactor.core.publisher.Mono;

public class CorsFilter implements WebFilter {

	public Mono<Void> filter(final ServerWebExchange serverWebExchange, final WebFilterChain webFilterChain) {
		// Adapted from
		// https://sandstorm.de/de/blog/post/cors-headers-for-spring-boot-kotlin-webflux-reactor-project.html
		serverWebExchange.getResponse().getHeaders().add("Access-Control-Allow-Origin", "*");
		if (serverWebExchange.getRequest().getMethod() == HttpMethod.OPTIONS) {
			serverWebExchange.getResponse().getHeaders().add("Access-Control-Max-Age", "1728000");
			return Mono.empty();
		} else {
			return webFilterChain.filter(serverWebExchange);


Testing the application

Now you can test the application using any client as per your choice. You can use curl command to access the services. You could create Java we client to access the services or even you can create your own client using ReactJS, Angular(JS) or any other technologies to consume the services.

Here I have used REST client to show you how to test the application in the below video.

The video does not include the testing for delete operation, so it’s left an exercise for you.


URL – http://localhost:8080/website/3

Headers – Content-Type : application/json

Response – 200

Congratulations! You have developed Spring Boot Functional Reactive Programming example.

You may also like to read Spring Boot + Angular Functional Reactive Programming

Source Code

download source code

Thanks for reading.

Author: Soumitra

Hi, I am, Soumitra, the owner of roytuts.com and it is my passion for sharing my knowledge and I have been writing blogs on various technologies since 2014. If you like my tutorials, you may also want to like my Facebook Page, follow me on Twitter, Github.

2 thoughts on “Spring Boot Functional Reactive Programming Example

Leave a Reply

Your email address will not be published. Required fields are marked *