Empower Your System with Dynamic Spring Reactive Redis Publisher/Subscriber Event Design 2208

You are currently viewing Empower Your System with Dynamic Spring Reactive Redis Publisher/Subscriber Event Design 2208
Empower Your System with Dynamic Spring Reactive Redis Publisher/Subscriber Event Design


In this article, we’ll explore the intricacies of crafting an event-driven architecture using the Reactive Redis Publisher/Subscriber .

Reactive Redis Overview:

Reactive Redis, in essence, is a powerful tool for implementing reactive programming paradigms. Its core functionality lies in the Publish/Subscribe model, allowing for efficient and scalable event-driven architectures. This model is particularly valuable when integrated with frameworks like Spring WebFlux, enabling developers to build responsive and real-time systems. For a deeper dive into its integration specifics, refer to the detailed discussion in the associated article.

Redis Publisher/Subscriber Model:

Pub/Sub stands as a messaging paradigm facilitating communication among various components within a distributed system. In this model, publishers dispatch messages to a specific topic, and subscribers, expressing interest in that topic, receive the messages. This structure maintains the anonymity of publishers while ensuring that the messages reach all relevant subscribers.

Redis Pub/Sub introduces a notable feature where messages sent by publishers to channels are actively pushed by Redis to all subscribed clients. This mechanism guarantees that subscribers receive the messages in the chronological order of their publication, enhancing the reliability and orderliness of communication in the system.

Application Configuration Using Spring Boot and Reactive Redis:

Technical Stack for the Project:

  • Spring Boot version 3.2.0
  • Java version 21
  • Redis
  • Docker

Starting Up Redis Server and Redis Insight:

Initiating the Redis server along with Redis Insight involves utilizing Docker, with the Redis server configured on port 6379 and Redis Insight on port 8001:

Docker run -d --call redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:today's

To set up the application, use Spring Initializer and include the following dependencies in the pom.xml file:

    <!-- Spring Boot Starter for Reactive Redis -->

    <!-- Spring Boot Starter for WebFlux -->

    <!-- Project Lombok for simplified Java code -->

    <!-- Reactor Test for testing reactive components -->

    <!-- SpringDoc OpenAPI Starter for WebFlux UI -->

Setting Up Configurations:

To configure the Spring Boot application, modify the application.yml file with the Redis-related settings as follows:

  host: localhost
  port: 6379

This configuration specifies that the Redis server is expected to be running on the local machine at the specified host (localhost) and port (6379). Adjust these settings according to your Redis server’s actual host and port if they differ. To configure the Spring Boot application, modify the application.yml file with the Redis-related settings as follows:

Reactive Redis Pub/Sub Configuration:

The RedisMessageListenerContainer serves as a crucial message-listener container, facilitating the reception of messages from a Redis channel and steering the injected MessageListener instances. Below is a rewritten note summarizing the provided configuration:

public class RedisConfig {

    private String host;

    private int port;

    public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() {
        return new LettuceConnectionFactory(host, port);

    public ReactiveRedisOperations reactiveRedisOperations(ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Product.class);

        RedisSerializationContext.RedisSerializationContextBuilder builder =
                RedisSerializationContext.newSerializationContext(new StringRedisSerializer());

        RedisSerializationContext context = builder.value(serializer).build();

        return new ReactiveRedisTemplate(reactiveRedisConnectionFactory, context);

public ReactiveRedisMessageListenerContainer messageListenerContainer(
        final ProductService productService,
        final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory
) {
        final ReactiveRedisMessageListenerContainer container = new ReactiveRedisMessageListenerContainer(reactiveRedisConnectionFactory);
        final ObjectMapper objectMapper = new ObjectMapper();

                .map(message -> {
                    try {
                        return objectMapper.readValue(message, Product.class);
                    } catch (IOException e) {
                        return null;
                .switchIfEmpty(Mono.error(new IllegalArgumentException()))
                .subscribe(c -> log.info("Product Saved Successfully."));

        return container;


This configuration demonstrates the setup of a Reactive Redis Pub/Sub system within a Spring Boot application, emphasizing the utilization of RedisMessageListenerContainer to handle messages from the “products” channel.Customizations can be made based on specific project requirements.

Product Publisher Class:

The ProductPublisher class functions as the Redis Publisher, responsible for publishing messages to the specified channel.

public class ProductPublisher {

    personal static very last string REDIS_CHANNEL = "PRODUCT_CHANNEL";
    private final ReactiveRedisOperations reactiveRedisOperations;

    public Mono publishProductMessage(final Product product) {
        this.reactiveRedisOperations.convertAndSend(REDIS_CHANNEL, product).subscribe(count -> {
            log.info("Product Published Successfully.");
        return Mono.just("Published Message to Redis Channel");


This class is annotated with @Component to indicate its role as a Spring component. It utilizes the ReactiveRedisOperations to publish a Product message to the designated Redis channel (“PRODUCT_CHANNEL”). The publishProductMessage method logs a success message upon successful publication and returns a Mono with a message indicating the successful message publication to the Redis channel.

Product Service Class:

The ProductService class, annotated with @Service, encapsulates operations related to the product domain.

public class ProductService {

    private final ReactiveRedisOperations reactiveRedisOperations;
    private static trailing string REDIS_KEY = "PRODUCT_REDIS";

    public Flux findAll() {
        return this.reactiveRedisOperations.opsForList().range(REDIS_KEY, 0, -1);

    public Mono save(final Product product) {
        final String id = UUID.randomUUID().toString().substring(0, 8);
        return this.reactiveRedisOperations.opsForList().rightPush(REDIS_KEY, product);


This service class, marked with @Service, provides methods for interacting with Redis using ReactiveRedisOperations. The findAll method retrieves all products from the Redis list, and the save method generates a unique ID for the product, sets it, and then saves the product to the Redis list. The class is designed to handle product-related operations in a reactive manner.

Product Controller Class:

public class ProductController {

    private final ProductService productService;
    private final ProductPublisher productPublisher;

    public Flux findAll() {
        return this.productService.findAll();

    public Mono publishProduct(@RequestBody final Product product) {
        return this.productPublisher.publishProductMessage(product);


In this class, the @GetMapping annotated method exposes an endpoint to retrieve all products, utilizing the findAll method from the injected ProductService. The @PostMapping(“/publish”) annotated method is responsible for publishing a product message to Redis, leveraging the ProductPublisher. The @RequestBody annotation ensures that the Product object is correctly mapped from the request body. This controller class provides a RESTful API for managing products, including retrieval and publication functionalities.

Testing the Application:

To assess the application’s functionality, we’ll employ Spring Doc Open API for publishing product messages to the Redis Channel. Follow these steps:

1.Publish Product Message to Redis Channel:

Utilize Spring Doc Open API to publish product messages effectively to the designated Redis channel.

2.Redis Insight Dashboard with Published Products:

Monitor the Redis Insight dashboard to visualize the products successfully published during testing.

3.Published Products in Redis Database:

Verify the presence of the published products within the Redis database.


In this article, we’ve delved into the following key areas:

Overview of Reactive Redis

Redis Publisher-Subscriber model

Docker-based initiation of Redis Server and Redis Insight

Integration of Reactive Redis Pub/Sub with Spring Boot

Testing REST endpoints through Spring Doc Open API

Feel free to share your valuable feedback. Thank you for your readership.

This Post Has 6 Comments

  1. Tigran Ayrapetyan


    We provide funding through our venture capital company to both start-up and existing companies either looking for funding for expansion or to accelerate growth in their company.
    We have a structured joint venture investment plan in which we are interested in an annual return on investment not more than 10% ROI. We are also currently structuring a convertible debt and loan financing of 3% interest repayable annually with no early repayment penalties.

    We would like to review your business plan or executive summary to understand a much better idea of your business and what you are looking to do, this will assist in determining the best possible investment structure we can pursue and discuss more extensively.

    I hope to hear back from you soon.


    Tigran Ayrapetyan
    Investment Director
    Devcorp International W.L.L.
    P.O Box 10236 Shop No. 305
    Flr 3 Manama Centre, Bahrain
    Email: ayrapetyantigran99@gmail.com

  2. Avtoservis_rfPt

    Качественный ремонт автомобилей на любой вкус
    Ремонт японских автомобилей [url=http://www.tokyogarage.ru]http://www.tokyogarage.ru[/url].

  3. LeslieMok

    эскорт работа

    Эскорт модели Индивидуалки Москвы, несомненно, являются украшением ночного города. Снять несложно в любом районе столицы, а предлагаемые клиентам интим услуги отличаются доступностью и большим разнообразием. Элитные проститутки по вызову в Мск позиционируют эротические услуги и секс за деньги, размещая интим объявления на нашем https: //mskvipladies.ru/ Воспользовавшись этим сайтом, любой москвич или гость столицы сможет найти ночную бабочку по своему вкусу и кошельку.


    [url=https://mskvipladies.ru/modeli/soderjanki-moskvy/]эскорт работа[/url]

  4. mnogofakto_wwet

    Сравнение методов многофакторной аутентификации
    двухфакторная аутентификация rdp [url=https://www.mnogofaktornaya-autentifikaciya.ru]впн кз[/url] .

  5. LeslieMok

    модели для кс 1 и 6

    Скачать CS 1.6, в поиске сервера со всех платных мониторингов! Русский чат, HD · High FPS модели или HD. Выбор языка игры.


    [url=https://cs-likes.ru/skachat-css-v34.html#comment-739]модели для кс 1 и 6[/url]

Leave a Reply