Pub/Sub Messaging with Go and Redis

Pub/Sub Messaging with Go and Redis

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 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 Go:

package main

import (
    "context"
    "fmt"
    "github.com/redis/go-redis/v9"
    "sync"
    "time"
)

var ctx = context.Background()

func messageHandler(message *redis.Message) {
    fmt.Printf("Received message: %s\n", message.Payload)
}

func main() {
    rdb := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        DB:   0,
    })

    // Subscribe to a channel
    pubsub := rdb.Subscribe(ctx, "notifications")
    defer pubsub.Close()

    var wg sync.WaitGroup
    wg.Add(1)

    // Run a goroutine to handle incoming messages
    go func() {
        defer wg.Done()
        for msg := range pubsub.Channel() {
            messageHandler(msg)
        }
    }()

    // Publish a message to the channel
    publishResult, err := rdb.Publish(ctx, "notifications", "Hello, Redis!").Result()
    if err != nil {
        fmt.Println("Error publishing:", err)
    } else {
        fmt.Printf("Message published, number of subscribers that received the message: %d\n", publishResult)
    }
    
    time.Sleep(1)

    // Unsubscribe before closing the channel to ensure clean communication closure
    err = pubsub.Unsubscribe(ctx, "notifications")
    if err != nil {
        fmt.Println("Error unsubscribing:", err)
    }

    // Ensure the subscriber channel is closed to exit the goroutine
    pubsub.Close()

    wg.Wait()
}

Let's break down the code snippet above:

  • First, we create a messageHandler function that prints the message received.
  • Then, we create a pubsub object and subscribe to the notifications channel.
  • We define a goroutine to listen for messages using pubsub.Channel() and call the messageHandler function when a message is received.
  • We use a sync.WaitGroup to ensure we wait for our goroutine to finish before the program exits.
  • Finally, we publish a message to the channel notifications after a short delay and print the number of subscribers that received the message. Additionally, the messageHandler function will print the message received, and the output will be:
Message published, number of subscribers that received the message: 1
Received message: Hello, Redis!

Note that we use the Unsubscribe method and a sync.WaitGroup to stop listening to messages and ensure our goroutine completes properly.

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