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

snippet
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()
}