Lab 08: Redis with Go
Overview
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)
}Step 2: String Operations
Step 3: Hash Operations
Step 4: Sorted Set — Leaderboard
Step 5: Pipeline & TxPipeline
Step 6: Pub/Sub
Step 7: Redis Streams
Step 8: Capstone — Full Demo with Live Redis
Summary
Data Structure
Key Commands
Use Case
Last updated
