redis

package
v2.13.0 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package redis provides an instrumented Redis client that implements app.Component.

The client wraps go-redis and supports single-node, Sentinel, and Cluster topologies through a unified Config. OpenTelemetry tracing and Prometheus metrics are applied as hooks at construction time and require no changes to call sites.

Use Client.Redis to obtain the underlying goredis.UniversalClient for executing commands.

Basic usage

client, err := redis.NewWithConfig(&redis.Config{
    Addrs: []string{"localhost:6379"},
})
if err != nil { log.Fatal(err) }

a.Register(client)
if err := a.Start(ctx); err != nil { log.Fatal(err) }
defer a.Shutdown(ctx) //nolint:errcheck

val, err := client.Redis().Get(ctx, "my-key").Result()

With tracing and metrics

client, err := redis.NewWithConfig(&redis.Config{
    Addrs:      []string{"localhost:6379"},
    Tracer:     a.Tracer(),
    Registerer: a.Metrics().Registerer(),
})

Every command automatically receives an OpenTelemetry span and is counted in Prometheus histograms.

Sentinel (high-availability)

client, err := redis.NewWithConfig(&redis.Config{
    Addrs:      []string{"sentinel1:26379", "sentinel2:26379"},
    MasterName: "mymaster",
})

In security-hardened deployments Sentinel processes require their own credentials, distinct from the Redis data-tier credentials:

client, err := redis.NewWithConfig(&redis.Config{
    Addrs:            []string{"sentinel1:26379", "sentinel2:26379"},
    MasterName:       "mymaster",
    SentinelUsername: "sentinel-user",
    SentinelPassword: "sentinel-secret",
    Password:         "redis-secret",
})

Cluster

client, err := redis.NewWithConfig(&redis.Config{
    Addrs: []string{"node1:6379", "node2:6379", "node3:6379"},
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an instrumented Redis client that implements app.Component. Call [Start] to verify connectivity and [Shutdown] to close all connections.

Client.Redis returns the underlying goredis.UniversalClient, which supports single-node, Sentinel, and Cluster topologies through a single consistent interface.

func NewWithConfig

func NewWithConfig(cfg *Config) (*Client, error)

NewWithConfig returns a Client configured with cfg. The underlying go-redis connection is lazy: no network calls are made until [Start] or the first command is executed.

OTel tracing, Prometheus metrics, and structured logging hooks are registered at construction time when the corresponding Config fields are non-nil.

func (*Client) Name

func (c *Client) Name() string

Name returns the component name for use in logs and error messages.

func (*Client) Redis

func (c *Client) Redis() goredis.UniversalClient

Redis returns the underlying goredis.UniversalClient for executing commands. The client is safe to use before [Start] — go-redis connects lazily — but [Start] should be called during application startup to verify connectivity before serving traffic.

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

Shutdown closes the Redis connection and releases all resources. It satisfies app.Component and should be called via app.App.Shutdown.

func (*Client) Start

func (c *Client) Start(ctx context.Context) error

Start pings the Redis server to verify connectivity. It satisfies app.Component and should be called via app.App.Start.

type Config

type Config struct {
	// Addrs is one or more Redis server addresses.
	//   Single-node:  []string{"localhost:6379"}
	//   Cluster:      multiple node addresses
	//   Sentinel:     sentinel addresses (also set MasterName)
	// Required: NewWithConfig returns an error if Addrs is empty.
	Addrs []string

	// MasterName is the Redis Sentinel master name.
	// Setting this enables Sentinel (failover) mode.
	MasterName string

	// SentinelUsername is the ACL username for authenticating to Sentinel
	// processes. Only applies when MasterName is set. Leave empty to use
	// the default user.
	SentinelUsername string

	// SentinelPassword is the AUTH password for Sentinel processes.
	// Only applies when MasterName is set. This is distinct from Password,
	// which authenticates to the Redis data nodes.
	SentinelPassword string

	// Username is the Redis ACL username (Redis 6+). Leave empty when using
	// the default user.
	Username string

	// Password is the Redis AUTH password.
	Password string

	// DB is the logical database number. Only applies to single-node and
	// Sentinel modes; ignored for Cluster. Defaults to 0.
	DB int

	// DialTimeout is the timeout for establishing new connections.
	// Defaults to the go-redis default (5s).
	DialTimeout time.Duration

	// ReadTimeout is the timeout for socket reads. Use -1 to disable.
	// Defaults to the go-redis default (3s).
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for socket writes. Use -1 to disable.
	// Defaults to ReadTimeout.
	WriteTimeout time.Duration

	// PoolSize is the maximum number of connections in the pool per node.
	// Defaults to the go-redis default (10 * runtime.NumCPU()).
	PoolSize int

	// MinIdleConns is the minimum number of idle connections to keep open.
	// Use this to pre-warm the pool at startup and avoid cold-start latency
	// on the first burst of requests.
	MinIdleConns int

	// MaxIdleConns is the maximum number of idle connections retained in the
	// pool. Zero means no limit.
	MaxIdleConns int

	// PoolTimeout is how long to wait for an available connection when the
	// pool is exhausted. Defaults to ReadTimeout + 1s.
	PoolTimeout time.Duration

	// ConnMaxIdleTime is the maximum duration a connection may sit idle
	// before being closed. Defaults to the go-redis default (30 minutes).
	// Set to -1 to disable idle timeout.
	ConnMaxIdleTime time.Duration

	// ConnMaxLifetime is the maximum duration a connection may be reused
	// before being closed. Zero means no limit.
	ConnMaxLifetime time.Duration

	// MaxRetries is the maximum number of retries before giving up on a
	// command. Defaults to the go-redis default (3 retries).
	// Set to -1 to disable retries.
	MaxRetries int

	// MinRetryBackoff is the minimum backoff between retries.
	// Defaults to the go-redis default (8ms). Set to -1 to disable backoff.
	MinRetryBackoff time.Duration

	// MaxRetryBackoff is the maximum backoff between retries.
	// Defaults to the go-redis default (512ms). Set to -1 to disable backoff.
	MaxRetryBackoff time.Duration

	// TLSConfig enables TLS for all connections when set. Uses the standard
	// crypto/tls.Config; see https://pkg.go.dev/crypto/tls#Config.
	TLSConfig *tls.Config

	// Name identifies this client in logs, errors, and as a constant label on
	// all Prometheus metrics. Defaults to "redis".
	//
	// Each client registered against the same Registerer must have a distinct
	// Name. Reusing a name causes NewWithConfig to return an error, because
	// sharing metric descriptors would silently drop pool stats and aggregate
	// command metrics across logically distinct clients.
	Name string

	// Namespace is the Prometheus metric namespace prepended to every metric
	// name. Defaults to "gitlab".
	Namespace string

	// Subsystem is the Prometheus metric subsystem. Defaults to "redis".
	// Together with Namespace this produces names of the form
	// gitlab_redis_command_duration_seconds.
	Subsystem string

	// Tracer enables OpenTelemetry span recording per command.
	// When nil, tracing is disabled.
	Tracer *trace.Tracer

	// Registerer is the Prometheus registerer used to publish Redis metrics.
	// When nil, Prometheus metrics are not collected.
	Registerer prometheus.Registerer

	// Logger is used for structured log entries per command and pipeline. When
	// nil, no log output is produced. The client name is automatically included
	// on every entry — callers do not need to set it manually.
	Logger *slog.Logger
}

Config holds optional configuration for NewWithConfig.

Jump to

Keyboard shortcuts

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