Implementing Pub/Sub Mechanism in C# Applications

Pub/Sub Messaging

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.

Redis Pub/Sub follows a fire-and-forget model, meaning messages are only delivered to subscribers that are actively listening at the time of publication. Unlike Redis Streams, there is no message persistence, meaning if a subscriber disconnects, it will miss messages sent during that time.

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 between different parts of your application. This is useful for creating real-time features like notifications, chat systems, or live updates.

Here's a sneak peek at how you can set up a simple Pub/Sub system in Redis:

using StackExchange.Redis;
using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
    private static readonly ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
    private static readonly ISubscriber subscriber = redis.GetSubscriber();

    static void Main(string[] args)
    {
        // Subscriber part
        Task.Run(() =>
        {
            subscriber.Subscribe("notifications", (channel, message) =>
            {
                Console.WriteLine($"Received message: {message}");
            });
        });

        // Give some time for the subscription to be set up
        Thread.Sleep(1000);

        // Publisher part
        long publishResult = subscriber.Publish("notifications", "Hello, Redis!");
        Console.WriteLine($"Message published, number of subscribers that received the message: {publishResult}");

        // Let the subscriber run for some time to ensure it receives the message
        Thread.Sleep(2000);

        // Unsubscribe (clean up is automatic on exit)
        subscriber.Unsubscribe("notifications");
    }
}

Let's break down the code snippet above:

  • We connect to Redis using ConnectionMultiplexer.Connect.
  • We use GetSubscriber to obtain a Redis subscriber.
  • We subscribe to the notifications channel and define a lambda function to handle incoming messages by printing them to the console.
  • We introduce a delay with Thread.Sleep to wait before publishing a message.
  • We publish a message to the notifications channel using Publish and output the number of subscribers that received the message.
  • Finally, we unsubscribe from the channel and close the Redis connection.

The subscription runs on a separate thread using Task.Run(), allowing it to listen for messages without blocking the main thread. However, in real-world applications, it is better to use an event-driven model rather than Thread.Sleep(), which is used here only for demonstration purposes.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal