Spring Data Redis Messaging – PubSub example | Spring Boot

The previous post introduces way to do Redis CRUD Operations. In this tutorial, we’re gonna look at how to implement Redis Messaging- PubSub with Spring Boot.

Related Post: Spring Data Redis CRUD Operations example with Spring Boot

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.9.0.RELEASE
– Spring Boot: 1.5.9.RELEASE

II. Spring Data Redis Messaging – PubSub

1. Overview

Spring Data provides dedicated messaging integration for Redis that can be roughly divided into two areas of functionality: production (or publication) and consumption (or subscription) of messages.

– Publisher doesn’t know specific subscribers to send messages to. Instead, Publisher specifies channel.
– Subscriber receives messages from one or more topics, without knowledge of Publisher.

2. Maven Dependency

3. Redis Configuration

We need:
– connection factory -> JedisConnectionFactory
– a channel -> ChannelTopic
– a template for publisher to publish messages -> RedisTemplate
– a message listener for consumer to consume messages -> RedisMessageListenerContainer

We can also supply an executor within RedisMessageListenerContainer for asynch manner of messages.

4. Publish Message

We use convertAndSend() method of the redisTemplate to format and publish message to topic.

When a message is published, it goes to all the subscribers.

5. Subscribe to Message

We implement the Spring Data Redis-provided MessageListener interface and handle received Message in onMessage() method:

III. Practice

1. Project Structure


2. Step by Step
1. Create Spring Boot project & add Dependencies

2. Create DataModel Class

Under package model, create Customer class:

3. Create Publisher

Under package producer:
CustomerInfoPublisher interface:

– And its implementation:

4. Create Subscriber

Under package consumer:

5. Configure Spring Data Redis

Under package config, create RedisConfig class:

6. Application Class

7. Run Spring Boot Application & Check Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results:

IV. Source Code


By grokonez | January 3, 2018.

Related Posts

2 thoughts on “Spring Data Redis Messaging – PubSub example | Spring Boot”

  1. Hi Team,

    Need help asap.

    Caused by: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool

    Many Thanks

Got Something To Say:

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