DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Application Listeners
  • A Robust Distributed Payment Network With Enchanted Audit Functionality - Part 2: Spring Boot, Axon, and Implementation
  • How To Get Closer to Consistency in Microservice Architecture
  • Leveraging Salesforce Using a Client Written In Vue.js

Trending

  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • Why Documentation Matters More Than You Think
  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  1. DZone
  2. Coding
  3. Frameworks
  4. Event Streaming Using Spring WebFlux

Event Streaming Using Spring WebFlux

In Spring Framework 5, a new module was released for supporting reactive applications called WebFlux. Check out this post to learn more.

By 
Marco Giglione user avatar
Marco Giglione
·
Jul. 20, 18 · Analysis
Likes (15)
Comment
Save
Tweet
Share
58.7K Views

Join the DZone community and get the full member experience.

Join For Free

Overview

Spring Framework 5 includes a new WebFlux module for supporting reactive applications. If we want systems that are responsive, resilient, elastic, and message-driven, then we need to introduce “reactive systems.”

It was created to solve the problem of the need for a non-blocking web stack to handle concurrency with a small number of threads. The term “reactive” refers to programming models that are built around reacting to change. In this regard, non-blocking is reactive, because, instead of being blocked, we are now in the mode of reacting to notifications as operations complete or data becomes available.

It is fully non-blocking and supports reactive streams back pressure, running on servers such as Netty, Undertow, and Servlet 3.1+ containers.

Image title

About Non-Blocking

Usually, when a client makes a request for a servlet, I/O on the server is managed by a specific thread taken from a limited pool. If the operation is time extensive or has some latency, for example, because we are calling another service, the I/O results in a blocked state until we get a response. This could not be a problem in a system with a small load, but it can limit performance on a high scaling one. One solution could be to rise up thread pool size, but this cannot be a good idea, due to increased resources consumption. In Spring WebFlux and non-blocking servers in general, it is assumed that applications will not block, and, therefore, non-blocking servers use a small, fixed-size thread pool (event loop workers) to handle requests. Nodejs is able to serve thousands of requests with only one thread!

Data Types

Spring uses behind the scenes Reactor (https://projectreactor.io/) as the library to structure their new APIs.

 Flux  and Mono are the two main concepts involved in reactive programming. Both are implementations of Publisher  interface, but Flux  produces 0 to N items, while Mono produces 0 to 1 item.

The Sample System

For testing purposes, let's suppose that we need to create a service that continuously monitors the temperature of an object (in Celsius), in an IoT-style manner:

Preparations

We’ll set up the following dependency:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>


Server Part

Now, let’s start to create the controller responsible for generating temperatures:

import java.time.Duration;
import java.util.Random;
import java.util.stream.Stream;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Flux;

@RestController
public class TemperatureController {

    Logger logger = LoggerFactory.getLogger(TemperatureController.class);

    @GetMapping(value = "/temperatures", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Integer> getTemperature() {
        Random r = new Random();
        int low = 0;
        int high = 50;
        return Flux.fromStream(Stream.generate(() -> r.nextInt(high - low) + low)
            .map(s -> String.valueOf(s))
            .peek((msg) -> {
                logger.info(msg);
            }))
            .map(s -> Integer.valueOf(s))
            .delayElements(Duration.ofSeconds(1));
    }
}


The server part consists of a  RestController that has a route responding to the /temperatures  path using GET HTTP method. Flux  is the reactive component that we use to send multiple objects to the client. We can create this in many different ways, but, for this simple scenario, we used the generation starting from a Java 8 stream.

The  delayElementsmethod is used to insert a delay for every item sent to the client.

Client Part

Now, let’s write down a simple Spring Boot client application that connects to the server and retrieves temperatures from that.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;

@SpringBootApplication(scanBasePackages = { "com.mgiglione" })
public class TemperatureClient {

    Logger logger = LoggerFactory.getLogger(TemperatureClient.class);

    @Bean
    WebClient getWebClient() {
        return WebClient.create("http://localhost:8081");
    }

    @Bean
    CommandLineRunner demo(WebClient client) {
        return args -> {
            client.get()
                .uri("/temperatures")
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(Integer.class)
                .map(s -> String.valueOf(s))
                .subscribe(msg -> {
                    logger.info(msg);
                });
        };
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(TemperatureClient.class).properties(java.util.Collections.singletonMap("server.port", "8081"))
            .run(args);
    }


}


The client makes use of the WebClient class to manage the connection with the server part. Once we have a specified URL and media type accepted by the client, we can retrieve the flux and subscribe to each event sent on it, in this case, printing each element on the console.

Conclusions

In this article, we have seen how to produce and consume a stream of data in a reactive way using the new Spring WebFlux module. All of the code snippets that were mentioned in the article can be found in my Github repository.

Spring Framework Event

Published at DZone with permission of Marco Giglione, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Application Listeners
  • A Robust Distributed Payment Network With Enchanted Audit Functionality - Part 2: Spring Boot, Axon, and Implementation
  • How To Get Closer to Consistency in Microservice Architecture
  • Leveraging Salesforce Using a Client Written In Vue.js

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!