Lab 08: Redis with Go

Time: 45 minutes | Level: Advanced | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

Master go-redis/v9: String/Hash/Sorted Set operations, Pipeline/TxPipeline, Pub/Sub, and Redis Streams. Run with a live Redis container.


Step 1: Client Setup

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

func newRedisClient() *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:         "localhost:6379",
		Password:     "",   // no auth
		DB:           0,    // default DB
		DialTimeout:  2 * time.Second,
		ReadTimeout:  3 * time.Second,
		WriteTimeout: 3 * time.Second,
		PoolSize:     10,
	})
}

// Cluster client (for production Redis Cluster)
func newClusterClient() *redis.ClusterClient {
	return redis.NewClusterClient(&redis.ClusterOptions{
		Addrs: []string{
			"redis-node1:7000",
			"redis-node2:7001",
			"redis-node3:7002",
		},
	})
}

func main() {
	ctx := context.Background()
	rdb := newRedisClient()
	defer rdb.Close()

	// Ping
	pong, err := rdb.Ping(ctx).Result()
	if err != nil {
		fmt.Println("Redis not available:", err)
		return
	}
	fmt.Println("PING:", pong)
}

Start Redis:


Step 2: String Operations


Step 3: Hash Operations


Step 4: Sorted Set — Leaderboard


Step 5: Pipeline & TxPipeline

💡 Pipeline vs TxPipeline: Pipeline sends all commands in one batch (not atomic). TxPipeline wraps in MULTI/EXEC (atomic). For optimistic locking, use WATCH + TxPipelined.


Step 6: Pub/Sub


Step 7: Redis Streams


Step 8: Capstone — Full Demo with Live Redis

📸 Verified Output:


Summary

Data Structure
Key Commands
Use Case

String

Set/Get/Incr/SetNX

Sessions, counters, locks

Hash

HSet/HGetAll/HIncrBy

User profiles, config

Sorted Set

ZAdd/ZRevRange/ZRank

Leaderboards, priority queues

Pipeline

rdb.Pipeline()

Batch commands, reduce RTT

TxPipeline

rdb.TxPipeline()

Atomic MULTI/EXEC

Pub/Sub

Subscribe/Publish

Real-time notifications

Streams

XAdd/XRead/XGroup

Event sourcing, message queues

Key Takeaways:

  • SetNX + Del = basic distributed lock (use Redlock for production)

  • Pipeline reduces latency by batching; TxPipeline adds atomicity

  • Sorted sets are O(log N) for add/remove, O(log N + M) for range queries

  • Redis Streams persist messages — Pub/Sub does not (fire-and-forget)

  • Use PoolSize and timeouts to handle connection pool exhaustion

Last updated