Lesson 5
Implementing Pub/Sub for Real-Time Notifications with Go and Redis
Implementing Pub/Sub for Notifications

Welcome! In this unit, we will delve into implementing Pub/Sub for notifications within our Redis-based backend system project. You've already learned how to manage user data, handle transactions, and use streams for event logging. Now, we'll add another powerful feature to our project: real-time notifications using Redis Pub/Sub (publish/subscribe). This addition will enable our system to send and receive messages instantaneously.

What You'll Build

In this unit, we'll focus on creating a simple real-time notification system using Redis Pub/Sub with Go. Specifically, we'll cover:

  1. Publishing Messages: How to send notifications.
  2. Subscribing to Channels: How to receive and handle notifications.

Here is a quick refresher on how Pub/Sub works in Redis using Go:

Go
1package main 2 3import ( 4 "fmt" 5 "github.com/redis/go-redis/v9" 6 "context" 7 "time" 8) 9 10var ctx = context.Background() 11var client = redis.NewClient(&redis.Options{ 12 Addr: "localhost:6379", 13 DB: 0, 14}) 15 16// Function to publish messages to a channel 17func publishMessage(channel string, message map[string]string) { 18 err := client.Publish(ctx, channel, fmt.Sprintf("%s: %s", message["user"], message["text"])).Err() 19 if err != nil { 20 fmt.Printf("Could not publish message: %s\n", err) 21 } 22} 23 24// Function to handle incoming messages 25func messageHandler(message *redis.Message) { 26 fmt.Printf("Received message: %s\n", message.Payload) 27} 28 29func main() { 30 channelName := "chat_room" 31 pubsub := client.Subscribe(ctx, channelName) 32 _, err := pubsub.Receive(ctx) 33 if err != nil { 34 panic(err) 35 } 36 37 go func() { 38 ch := pubsub.Channel() 39 for msg := range ch { 40 messageHandler(msg) 41 } 42 }() 43 44 message := map[string]string{"user": "alice", "text": "Hello everyone!"} 45 publishMessage(channelName, message) 46 47 // Giving some time for the subscription to set up and for messages to be processed 48 time.Sleep(1 * time.Second) 49 pubsub.Close() 50}

In this snippet, messageHandler processes incoming messages on the chat_room channel. The publishMessage function sends a message to the specified channel. The messages are received by messageHandler and printed to the console.

Exciting, isn’t it? Now, it's time to put this into practice. Let's implement the complete code to build our real-time notification system.

Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.