Redis PubSub Messaging
Introduction
Welcome back! In this lesson, we will dive into another powerful feature of Redis: Publish/Subscribe (Pub/Sub) messaging. This topic builds on our understanding of Redis and introduces a dynamic way to enable real-time communication within your applications.
What You'll Learn
In this lesson, you will learn how to set up and use Redis Pub/Sub messaging to send and receive messages using C++ and Boost.Redis. We'll create a single program that demonstrates both subscribing to and publishing messages on a channel.
Important notes:
- Dedicated connection for subscribers: The subscriber uses a separate Redis connection that operates in subscription mode.
- Asynchronous event-driven model: We use Boost.Asio's
io_contextto handle asynchronous operations. - RESP3 push messages: Redis sends Pub/Sub messages as push events that we receive through
async_receive. - Two connections: One for subscribing (enters special subscriber mode) and one for regular commands like PUBLISH.
Setting Up the Connections
Let's start by setting up our includes and creating two Redis connections:
What's happening here:
- We create an
io_context, which is the event loop that drives all asynchronous operations. - We create two separate connections:
sub_connfor subscribing andpub_connfor publishing. - Why two connections? Once a connection enters subscriber mode (after SUBSCRIBE), it can only receive push messages and cannot execute regular commands. That's why we need a separate connection for PUBLISH.
- Both connections are started with
async_run(), which establishes the connection asynchronously.

