client

package
v1.8.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 8 Imported by: 6

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Close

func Close(client redis.UniversalClient) error

Close closes the Redis client connection. A nil client is a no-op.

func HealthCheck

func HealthCheck(ctx context.Context, client redis.UniversalClient) bool

HealthCheck performs a health check on the Redis connection Returns true if healthy, false otherwise

func NewClient

func NewClient(cfg Config) (*redis.Client, error)

NewClient creates a new Redis client with the given configuration

func NewClientContext added in v1.8.0

func NewClientContext(ctx context.Context, cfg Config) (*redis.Client, error)

NewClientContext creates a single-node client and verifies it with PING. ctx cancellation and the smaller of its deadline and DialTimeout bound the entire startup, including dialing, TLS, authentication and PING. Once this function returns, ctx does not control the lifetime of the client.

func NewClientWithDefaults

func NewClientWithDefaults(addr string) (*redis.Client, error)

NewClientWithDefaults creates a new Redis client with default configuration

func NewUniversalClient added in v1.7.0

func NewUniversalClient(cfg Config) (redis.UniversalClient, error)

NewUniversalClient creates whichever go-redis client the configuration describes: a Sentinel-backed failover client when MasterName is set, a cluster client when Addrs holds more than one address, and a single-node client otherwise. See redis.NewUniversalClient for the exact rules.

This is the constructor to use with the rest of redis-kit, whose constructors all take a redis.UniversalClient. NewClient remains the way to get a concrete *redis.Client when you need one -- to reach Options() or to pass it somewhere that still insists on the concrete type.

The field mapping is written out here rather than routed through redis.UniversalOptions.Simple, keeping the standalone field mapping explicit.

Example

NewUniversalClient builds whichever client the configuration describes: a Sentinel-backed failover client when MasterName is set, a cluster client for more than one address, and a single-node client otherwise. Compiled but not run: there is nothing here to connect to.

package main

import (
	"github.com/soulteary/redis-kit/client"
)

func main() {
	cluster, err := client.NewUniversalClient(
		client.DefaultConfig().WithAddrs("10.0.0.1:6379", "10.0.0.2:6379", "10.0.0.3:6379"),
	)
	if err != nil {
		return
	}
	defer func() { _ = client.Close(cluster) }()

	sentinel, err := client.NewUniversalClient(
		client.DefaultConfig().
			WithAddrs("10.0.0.1:26379", "10.0.0.2:26379").
			WithMasterName("mymaster").
			WithSentinelAuth("sentinel-user", "sentinel-pass"),
	)
	if err != nil {
		return
	}
	defer func() { _ = client.Close(sentinel) }()
}

func NewUniversalClientContext added in v1.8.0

func NewUniversalClientContext(ctx context.Context, cfg Config) (redis.UniversalClient, error)

NewUniversalClientContext selects the same client shape as NewUniversalClient, with the startup context semantics of NewClientContext.

func Ping

func Ping(ctx context.Context, client redis.UniversalClient) error

Ping tests the connection to Redis.

client is a redis.UniversalClient, so a standalone client, a cluster, a ring and a Sentinel-backed failover client are all accepted. A nil client -- including a typed nil such as an unassigned *redis.Client field -- is reported as an error rather than dereferenced.

Types

type Config

type Config struct {
	// Addr is the Redis server address (e.g., "localhost:6379")
	Addr string

	// Addrs is a seed list of host:port addresses, for a Redis Cluster or for
	// the Sentinel nodes of a failover setup. It is read only by
	// [NewUniversalClient]; [NewClient] always builds a single-node client
	// from Addr. When it is empty, NewUniversalClient falls back to Addr.
	Addrs []string

	// MasterName is the Sentinel master name. Setting it makes
	// [NewUniversalClient] return a Sentinel-backed failover client, with
	// Addrs (or Addr) read as the Sentinel addresses rather than as Redis
	// servers.
	MasterName string

	// SentinelUsername and SentinelPassword authenticate to the Sentinel
	// nodes themselves. They are separate from Username/Password, which authenticate
	// to the Redis server Sentinel points at -- the two frequently differ,
	// and a Sentinel deployment with ACLs is unusable without them.
	SentinelUsername string
	SentinelPassword string

	// Username is the Redis ACL username. An empty value uses the default user.
	Username string

	// Password is the Redis password (empty if no password)
	Password string

	// TLSConfig enables TLS for Redis connections. Constructors clone this
	// configuration before passing it to go-redis. A custom Dialer owns its
	// transport, including TLS, when provided.
	TLSConfig *tls.Config

	// ContextTimeoutEnabled makes go-redis apply command context deadlines to
	// socket reads and writes. It defaults to false for compatibility. The
	// context-aware constructors always honor their startup context regardless
	// of this setting; it controls subsequent commands on the returned client.
	ContextTimeoutEnabled bool

	// DB is the Redis database number (default: 0)
	DB int

	// PoolSize is the maximum number of socket connections (default: 10)
	PoolSize int

	// MinIdleConns is the minimum number of idle connections (default: 5)
	MinIdleConns int

	// DialTimeout is the timeout for establishing connections (default: 5s)
	DialTimeout time.Duration

	// ReadTimeout is the timeout for socket reads (default: 3s)
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for socket writes (default: 3s)
	WriteTimeout time.Duration

	// MaxRetries is the maximum number of retries for failed commands (default: 3)
	MaxRetries int

	// PoolTimeout is the timeout for getting a connection from the pool (default: 4s)
	PoolTimeout time.Duration

	// Dialer is optional custom dialer (e.g. for mock in tests). When set, Addr can be a placeholder.
	Dialer Dialer
}

Config represents Redis client configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with default values

func (Config) WithAddr

func (c Config) WithAddr(addr string) Config

WithAddr sets the Redis server address

func (Config) WithAddrs added in v1.7.0

func (c Config) WithAddrs(addrs ...string) Config

WithAddrs sets the seed list of cluster or Sentinel addresses. Only NewUniversalClient reads it.

func (Config) WithContextTimeoutEnabled added in v1.8.0

func (c Config) WithContextTimeoutEnabled(enabled bool) Config

WithContextTimeoutEnabled controls whether command deadlines bound socket I/O.

func (Config) WithDB

func (c Config) WithDB(db int) Config

WithDB sets the Redis database number

func (Config) WithDialTimeout

func (c Config) WithDialTimeout(timeout time.Duration) Config

WithDialTimeout sets the dial timeout

func (Config) WithMasterName added in v1.7.0

func (c Config) WithMasterName(name string) Config

WithMasterName sets the Sentinel master name, selecting a failover client in NewUniversalClient.

func (Config) WithMaxRetries

func (c Config) WithMaxRetries(retries int) Config

WithMaxRetries sets the maximum number of retries. Use -1 to disable retries; go-redis interprets zero as its default, not as "no retries".

func (Config) WithMinIdleConns

func (c Config) WithMinIdleConns(minIdle int) Config

WithMinIdleConns sets the minimum number of idle connections

func (Config) WithPassword

func (c Config) WithPassword(password string) Config

WithPassword sets the Redis password

func (Config) WithPoolSize

func (c Config) WithPoolSize(size int) Config

WithPoolSize sets the connection pool size

func (Config) WithPoolTimeout

func (c Config) WithPoolTimeout(timeout time.Duration) Config

WithPoolTimeout sets the pool timeout

func (Config) WithReadTimeout

func (c Config) WithReadTimeout(timeout time.Duration) Config

WithReadTimeout sets the read timeout

func (Config) WithSentinelAuth added in v1.7.0

func (c Config) WithSentinelAuth(username, password string) Config

WithSentinelAuth sets the credentials used against the Sentinel nodes, which are not the credentials used against the Redis server behind them.

func (Config) WithTLSConfig added in v1.8.0

func (c Config) WithTLSConfig(config *tls.Config) Config

WithTLSConfig enables TLS. A nil configuration disables TLS. The value is cloned here and again by constructors to isolate top-level configuration changes.

func (Config) WithUsername added in v1.8.0

func (c Config) WithUsername(username string) Config

WithUsername sets the Redis ACL username (empty selects the default user).

func (Config) WithWriteTimeout

func (c Config) WithWriteTimeout(timeout time.Duration) Config

WithWriteTimeout sets the write timeout

type Dialer added in v1.0.1

type Dialer func(ctx context.Context, network, addr string) (net.Conn, error)

Dialer is the type for custom Redis connection dialer (optional, for testing or custom network).

type HealthStatus

type HealthStatus struct {
	Healthy   bool
	Latency   time.Duration
	Error     error
	Timestamp time.Time
}

HealthStatus represents the health status of a Redis connection

func CheckHealth

func CheckHealth(ctx context.Context, client redis.UniversalClient) HealthStatus

CheckHealth performs a comprehensive health check.

client is a redis.UniversalClient, so every go-redis client shape is accepted. A nil client -- including a typed nil -- is reported as an unhealthy status rather than dereferenced.

Example

CheckHealth reports reachability and latency without the caller having to decide what counts as healthy.

package main

import (
	"context"
	"fmt"

	"github.com/soulteary/redis-kit/client"
	"github.com/soulteary/redis-kit/testutil"
)

func main() {
	rdb, _ := testutil.NewMockRedisClient() // in real code, your own client
	defer func() { _ = rdb.Close() }()

	status := client.CheckHealth(context.Background(), rdb)

	fmt.Println("healthy:", status.Healthy)
	fmt.Println("error:", status.Error)
}
Output:
healthy: true
error: <nil>
Example (NilClient)

A nil client is reported rather than dereferenced, including the typed nil a caller gets from an unassigned field.

package main

import (
	"context"
	"fmt"

	"github.com/soulteary/redis-kit/client"
)

func main() {
	status := client.CheckHealth(context.Background(), nil)

	fmt.Println("healthy:", status.Healthy)
	fmt.Println("error:", status.Error)
}
Output:
healthy: false
error: redis client is nil

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL