How to Use Redis Pub/Sub in Go

Connect to Redis in Go using the official client library to subscribe to channels and listen for real-time messages.

Use the github.com/go-redis/redis/v8 client library to connect to Redis, subscribe to a channel, and listen for messages in a loop.

package main

import (
	"context"
	"fmt"
	"log"
	"github.com/go-redis/redis/v8"
)

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

	ctx := context.Background()
	sub := rdb.Subscribe(ctx, "mychannel")
	defer sub.Close()

	ch := sub.Channel()
	for msg := range ch {
		fmt.Println("Received:", msg.Payload)
	}
}

To publish a message, use rdb.Publish(ctx, "mychannel", "Hello World").