2. Spring WebFlux: Reactive micro service Practical guide Intro

George Gatheca
5 min readMay 8, 2021

--

On my previous article “Spring WebFlux: Reactive micro service Introduction” we discussed why one should think of using reactive spring to build a micro service specifically a REST API. On this article we are going to create a sample reactive API. NB:

Full code for this tutorial can be found on GitHub branch “2-practical-guide-intro” by visiting this link. https://github.com/gathecageorge/spring-webflux-rest-api-intro/tree/2-practical-guide-intro/

To get started you will need java setup on your machine. I will assume basic knowledge of java and spring. First create a spring project by going to https://start.spring.io/. You need to select the following dependencies. Alternatively you can click this link for preset configs.

  1. For project type select maven.
  2. For language select JAVA
  3. For Spring boot select any latest spring version (Not SNAPSHOT)
  4. For Project metadata enter your details as required. Checkout the one I used below:

Once you select all this dependencies, click generate to get a project zip downloaded to your machine. Then you need to extract the ZIP to a location in your machine and open it with your favourite IDE. I recommend using Jetbrains Intellij. You can download the community edition by following this link. Once all this is done you are ready to dive into code.

Coding a simple Rest API Endpoint

Once you open your project with Intellij, the first time will take some time while its downloading all dependencies required. Then you will be able to edit the code.

Create a controller and endpoint

First step will be to create a new controller and a http GET endpoint that will return a mono of string and invoke the endpoint using the browser.

Create a class “SampleController.java” on package “controller”.

package com.gatheca.reactivedemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class SampleController {
@GetMapping("/sample1")
Mono<String> sample1() {
return Mono.just("Hello world");
}
}

So we have a class SampleController, we have annotated it with “@RestController” and also added a method that returns “Mono<String>”. The method is annotated with “@GetMapping” to mean its accessible via http get method on location “/sample1” from base URL. To create a mono instance we are using Mono.just() and passing the string we want returned.

To run our application, open the main method class in my case “ReactiveDemoApplication” and click on green run button next to main method and choose “Run ReactiveDemoAp…main()”

To invoke the application on browser, just type “http://localhost:8080/sample1” on the browser. By default the application starts using port 8080. The output is as expected, having a string “Hello World” on the browser. Nothing interesting but we have just made the 1st endpoint in reactive spring.

Sample response

Make things interesting

Lets say we want to create an endpoint that provides real time prices for a stock. We want to return a list of integers in a reactive way. To do that we create another endpoint on the controller like below. You will notice we use flux instead of mono since we are providing more than 1 response. Inside Flux.just() we provide a list of items we want returned comma separated.

NOTE: The new endpoint is accessible through /sample2

Response from browser.

The browser responds with a list of numbers we provided

Well this is still not interesting. The browser is waiting for all results to be computed and returned at once. That is why its even displayed as a list on one line. We want to stream the prices as each is calculated. For that we make some small changes. We introduce a delay when returning the prices to simulate process of calculation or database call, then we add “.log” to show logs as each item is streamed. Also we add produces value to the “@GetMapping” to mean method can produce a stream for supported clients. Those without support will just wait till all data is returned to begin processing.

Allow streaming of values to client

Sample response from a browser that supports stream data.

Response from a browser or client that supports stream.

Sample response from tabbed postman that does not support stream data.

If the client does not support stream then the output will be in a single line, its waiting to until all data is loaded to display.

Here we can see console on the IDE showing logs as values are emitted to the client. As you can see, when data is first requested, client subscribes to get data and passes the request with start value. Every time a new value is available then an onNext event is published with the value. When all data is sent then an onComplete event is sent telling client not to expect any other set of data.

WHATS NEXT

So what’s next after this? Well checkout for the next articles on the series.

  1. Spring WebFlux: Reactive micro service Introduction
  2. Spring WebFlux: Reactive micro service Practical guide Intro (You are here)
  3. Spring WebFlux: Using Relational Database (MySQL & PostgreSQL)
  4. Spring WebFlux: Unit testing your REST API (Continuation)
  5. Spring WebFlux: Tips & Tricks, Common mistakes
  6. Spring WebFlux: Load testing using JMeter

Want to learn more, have a topic in JAVA you might need articles on or have questions? Reach out to me on my profile or via LinkedIn here.

Hello👋, Did you find this tutorial helpful, please click the clap 👏 button below to show your support for the author 👇. Also this will help the algorithm for others who are learning to see this story.

--

--

George Gatheca
George Gatheca

Written by George Gatheca

Senior Software Engineer; Spring Java enthusiast; Building scalable solutions; Reducing compute waste.