Go Redis Universal Client Configuration

Configure the go-redis universal client for single, sentinel, and cluster topologies, with pool sizing and timeout discipline.

GoData Fetching

Code

gosnippet
54 lines
package main

import (
	"context"
	"fmt"
	"time"

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

func newRedisClient() redis.UniversalClient {
	opts := &redis.UniversalOptions{
		Addrs:        []string{"127.0.0.1:6379"},
		DialTimeout:  2 * time.Second,
		ReadTimeout:  800 * time.Millisecond,
		WriteTimeout: 800 * time.Millisecond,

		PoolSize:        20,
		MinIdleConns:    5,
		PoolTimeout:     2 * time.Second,
		MaxIdleConns:    10,
		ConnMaxIdleTime: 5 * time.Minute,

		// 同一份配置可透明升级为哨兵或集群:
		// MasterName: "mymaster",
		// Sentinels:  []*redis.SentinelAddr{{...}},
		// 或 Addrs 直接给多个集群节点

		MaxRetries:      2,
		MinRetryBackoff: 50 * time.Millisecond,
		MaxRetryBackoff: 500 * time.Millisecond,
	}

	return redis.NewUniversalClient(opts)
}

func main() {
	client := newRedisClient()

	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	pipe := client.Pipeline()
	setCmd := pipe.Set(ctx, "session:42", "active", 30*time.Minute)
	ttlCmd := pipe.TTL(ctx, "session:42")
	_, err := pipe.Exec(ctx)
	if err != nil {
		fmt.Println("pipeline failed:", err)
		return
	}
	fmt.Println("set ok:", setCmd.Val(), "ttl:", ttlCmd.Val())

	defer client.Close()
}

What happens as it runs

Read it this way: everything runs through the functions newRedisClient and main, doing all the work.

Nothing falls through silently — 1 checkpoint test err != nil on the way through. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

What to watch for

  • External dependency: github.com/redis/go-redis/v9 — install it before running the snippet.

Putting it to use

The one signature that matters here is func newRedisClient() redis.UniversalClient

Look for the pipeline failed:, set ok: prefixes as the file executes; they connect every printed line to the step behind it.

The sequence newRedisClient lives in main; running the file triggers it.

Core lines

if err != nil {
	fmt.Println("pipeline failed:", err)
	return
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
return redis.NewUniversalClient(opts)

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `github.com/redis/go-redis/v9`. Add it to your project before running the snippet.