Overview

In this article I want to show how easily it is to create a reactive REST API with Spring Boot. I would like to take a simple Use Case and use this example to show how quick it is possible to create an “active” non-blocking REST API with Spring Boot.

In the last months and weeks I was working on two different modern mobile apps/ web apps. Quite quickly I realized that it can be very inconvenient if you have to ask an API from the client side all the time if there are changes. As you surely know you can do this by polling. But I don’t think this is very elegant. It also causes a lot of unnecessary traffic.

A technically more elegant solution would be if the consumer of the API could subscribe to an endpoint, and this endpoint would inform the client about changes.

I would like to use so-called Server-Sent Events (short: SSE) for this. Server-Sent-Events is a HTTP-Standard. It allows an application to process a unidirectional event stream and receive updates whenever the server sends data. At this point I would like to briefly explain why I chose SSE and not WebSockets. WebSockets provide bidirectional communication between client and server, SSE provides unidirectional communication. However, WebSockets are not a HTTP protocol and do not offer standards for error handling unlike SSE.

Scenario

In my current own project, which deals with the implementation of a platform for trainers and workouts, I have implemented a microservice that takes care of training courses. From this service I take one scenario as an example. The scenario to be considered is quite simple and clear.

The idea is that User A can create a new course and User B will get updated the list of available courses without reloading the page. The client component should not have to constantly poll the service.

For this we need to provide the following endpoints: one endpoint where the client can create a new course (POST), an endpoint that allows the client to retrieve all existing courses (GET). And of course, the most interesting: the already discussed SSE endpoint that allows consumers to stream events.

HTTP GET /course

HTTP GET /course/sse

HTTP POST /course

It is also important to me that we can realize this scenario with any database. In another service I had used a MongoDB that already provides a Reactive Stream implementation with the ReactiveMongoRepository. This means that the repository already returns Mono or Flux instead of T or List. I will report on my experiences using the ReactiveMongoRepository in another article.

#webflux #reactive #spring-boot #microservices #java

Creating a Reactive Restful API with Spring Boot
1.20 GEEK