redis

package
v2.0.54 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0, Apache-2.0 Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Redis client configuration

Config.NewClient returns a go-redis UniversalClient for standalone, cluster, or Sentinel connections. Shared credentials, TLS, timeouts, retries, and pool settings apply to all modes. GetUniversalOptions exposes the resolved settings for all modes. Both methods accept optional Option arguments: use cfg.NewClient(ctx) or cfg.NewClient(ctx, redis.WithSecretManager(secretManager)).

Use these fields under cache.redis.options or storage.redis:

# Standalone (existing configuration remains supported)
addr: localhost:6379

# Cluster with seed nodes
addrs:
  - redis-1:6379
  - redis-2:6379

# Cluster with a single configuration endpoint
addr: redis-cluster:6379
isClusterMode: true

# Sentinel: addrs are Sentinel endpoints, not Redis server endpoints
addrs:
  - sentinel-1:26379
  - sentinel-2:26379
masterName: mymaster
sentinelUsername: sentinel-user
sentinelPassword: sentinel-password
username: redis-user
password: redis-password

Each example is a separate configuration. addrs takes precedence over addr. Multiple addresses select cluster mode unless masterName selects Sentinel. Cluster supports database 0 only. Cluster and Sentinel connections use TCP. maxRedirects, readOnly, routeByLatency, and routeRandomly configure routing; readOnly selects replicas in Sentinel mode.

passwordSecretName and sentinelPasswordSecretName resolve passwords through an injected SecretManager. Cache supplies that manager; storage currently supports inline passwords or password files. useTLS enables TLS in all modes.

passwordPath loads the Redis password from a file, trimming surrounding whitespace like the Postgres config. A non-empty path takes precedence over password and passwordSecretName; file read failures return an error. It is supported in standalone, cluster, and Sentinel modes (for the Redis server password, independently of Sentinel credentials). sentinelPasswordPath provides the same behavior for the Sentinel password, taking precedence over sentinelPassword and sentinelPasswordSecretName.

Storage listings scan all cluster masters and deduplicate the results. Reference URLs use the first configured endpoint as their host.

To enable OpenTelemetry instrumentation on clients created by NewClient, supply providers as runtime options:

client, err := cfg.NewClient(ctx,
    redis.WithTracerProvider(tracerProvider),
    redis.WithMeterProvider(meterProvider),
)

Tracing and metrics are enabled independently through redisotel only when the corresponding non-nil provider is supplied. These options apply to standalone, cluster, and Sentinel clients. The caller owns the providers and their shutdown.

Redis metrics use redisotel-native and are process-wide. WithMeterProvider initializes them before the first client is created; later providers do not replace that provider. Applications combining components should call redis.InitMetrics at startup with a shared provider. The manager does this with the flyte service name when running all components. Tracing remains per-client via redisotel.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InitMetrics added in v2.0.54

func InitMetrics(provider metric.MeterProvider) error

InitMetrics initializes native Redis metrics for all clients in this process. Call before creating clients. Subsequent calls preserve the first provider; a nil provider leaves metrics uninitialized.

Types

type Config

type Config struct {
	// The network type, either tcp or unix.
	// Default is tcp.
	Network string
	// host:port address.
	Addr string `json:"addr"`

	// Addrs contains cluster seed addresses or Sentinel addresses. Takes precedence over Addr.
	// Multiple addresses select cluster mode unless MasterName is set.
	Addrs []string `json:"addrs,omitempty"`
	// IsClusterMode enables cluster mode even with a single seed address.
	IsClusterMode bool `json:"isClusterMode,omitempty"`
	// MasterName selects Sentinel mode and identifies the monitored Redis master.
	MasterName string `json:"masterName,omitempty"`
	// Sentinel credentials are separate from Redis server credentials.
	SentinelUsername           string `json:"sentinelUsername,omitempty"`
	SentinelPassword           string `json:"sentinelPassword,omitempty"`
	SentinelPasswordSecretName string `json:"sentinelPasswordSecretName,omitempty"`
	// SentinelPasswordPath loads the Sentinel password from a file, trimming
	// surrounding whitespace. Takes precedence over SentinelPassword and SentinelPasswordSecretName.
	SentinelPasswordPath string `json:"sentinelPasswordPath,omitempty" pflag:",Points to the file containing the Sentinel password."`
	// Cluster routing and redirection settings. ReadOnly also selects Sentinel replicas.
	MaxRedirects   int  `json:"maxRedirects,omitempty"`
	ReadOnly       bool `json:"readOnly,omitempty"`
	RouteByLatency bool `json:"routeByLatency,omitempty"`
	RouteRandomly  bool `json:"routeRandomly,omitempty"`

	// ClientName will execute the `CLIENT SETNAME ClientName` command for each conn.
	ClientName string

	// Protocol 2 or 3. Use the version to negotiate RESP version with redis-server.
	// Default is 3.
	Protocol int
	// Use the specified Username to authenticate the current connection
	// with one of the connections defined in the ACL list when connecting
	// to a Redis 6.0 instance, or greater, that is using the Redis ACL system.
	Username string `json:"username"`
	// Optional password. Must match the password specified in the
	// requirepass server configuration option (if connecting to a Redis 5.0 instance, or lower),
	// or the User Password when connecting to a Redis 6.0 instance, or greater,
	// that is using the Redis ACL system.
	Password string `json:"password"`

	// PasswordPath points to a file containing the Redis password. Its contents are
	// trimmed of surrounding whitespace, as with Postgres. Takes precedence over
	// Password and PasswordSecretName.
	PasswordPath string `json:"passwordPath" pflag:",Points to the file containing the Redis password."`

	// PasswordSecretName is the name of the secret that contains the password.
	PasswordSecretName string

	// Database to be selected after connecting to the server.
	DB int `json:"db"`

	// Maximum number of retries before giving up.
	// Default is 3 retries; -1 (not 0) disables retries.
	MaxRetries int
	// Minimum backoff between each retry.
	// Default is 8 milliseconds; -1 disables backoff.
	MinRetryBackoff config.Duration
	// Maximum backoff between each retry.
	// Default is 512 milliseconds; -1 disables backoff.
	MaxRetryBackoff config.Duration

	// Dial timeout for establishing new connections.
	// Default is 5 seconds.
	DialTimeout config.Duration
	// Timeout for socket reads. If reached, commands will fail
	// with a timeout instead of blocking. Supported values:
	//   - `0` - default timeout (3 seconds).
	//   - `-1` - no timeout (block indefinitely).
	//   - `-2` - disables SetReadDeadline calls completely.
	ReadTimeout config.Duration
	// Timeout for socket writes. If reached, commands will fail
	// with a timeout instead of blocking.  Supported values:
	//   - `0` - default timeout (3 seconds).
	//   - `-1` - no timeout (block indefinitely).
	//   - `-2` - disables SetWriteDeadline calls completely.
	WriteTimeout config.Duration
	// ContextTimeoutEnabled controls whether the client respects context timeouts and deadlines.
	// See https://redis.uptrace.dev/guide/go-redis-debugging.html#timeouts
	ContextTimeoutEnabled bool

	// Type of connection pool.
	// true for FIFO pool, false for LIFO pool.
	// Note that FIFO has slightly higher overhead compared to LIFO,
	// but it helps closing idle connections faster reducing the pool size.
	PoolFIFO bool
	// Base number of socket connections.
	// Default is 10 connections per every available CPU as reported by runtime.GOMAXPROCS.
	// If there is not enough connections in the pool, new connections will be allocated in excess of PoolSize,
	// you can limit it through MaxActiveConns
	PoolSize int
	// Amount of time client waits for connection if all connections
	// are busy before returning an error.
	// Default is ReadTimeout + 1 second.
	PoolTimeout config.Duration
	// Minimum number of idle connections which is useful when establishing
	// new connection is slow.
	// Default is 0. the idle connections are not closed by default.
	MinIdleConns int
	// Maximum number of idle connections.
	// Default is 0. the idle connections are not closed by default.
	MaxIdleConns int
	// Maximum number of connections allocated by the pool at a given time.
	// When zero, there is no limit on the number of connections in the pool.
	MaxActiveConns int
	// ConnMaxIdleTime is the maximum amount of time a connection may be idle.
	// Should be less than server's timeout.
	//
	// Expired connections may be closed lazily before reuse.
	// If d <= 0, connections are not closed due to a connection's idle time.
	//
	// Default is 30 minutes. -1 disables idle timeout check.
	ConnMaxIdleTime config.Duration
	// ConnMaxLifetime is the maximum amount of time a connection may be reused.
	//
	// Expired connections may be closed lazily before reuse.
	// If <= 0, connections are not closed due to a connection's age.
	//
	// Default is to not close idle connections.
	ConnMaxLifetime config.Duration

	// TLS Config to use. When set, TLS will be negotiated. Not settable from a
	// config file; use UseTLS for config-driven TLS.
	TLSConfig *tls.Config

	// UseTLS negotiates TLS using the system certificate pool. Prefer this over
	// TLSConfig when configuring from YAML/JSON, where TLSConfig cannot be set.
	// Ignored when TLSConfig is already provided.
	UseTLS bool

	// TLSInsecureSkipVerify disables server certificate verification. Only set
	// this for testing against self-signed certificates.
	TLSInsecureSkipVerify bool

	// // Disable set-lib on connect. Default is false.
	DisableIndentity bool
}

Config contains the Redis client settings shared by cache and storage. Function-valued go-redis options are omitted so it can be used in config files.

func (Config) Addresses

func (r Config) Addresses() []string

Addresses returns configured endpoints, falling back to the legacy Addr field.

func (Config) GetUniversalOptions

func (r Config) GetUniversalOptions(ctx context.Context, opts ...Option) (*redis.UniversalOptions, error)

GetUniversalOptions resolves settings for standalone, cluster, or Sentinel clients. Use WithSecretManager when a password secret is configured.

func (Config) NewClient

func (r Config) NewClient(ctx context.Context, opts ...Option) (redis.UniversalClient, error)

NewClient creates the client selected by the configured addresses and MasterName. Use WithSecretManager when a password secret is configured.

type Option

type Option func(*configOptions)

Option supplies a runtime dependency when resolving Redis configuration.

func WithMeterProvider

func WithMeterProvider(provider metric.MeterProvider) Option

WithMeterProvider initializes process-wide Redis metrics if not already initialized. The first provider wins; initialize metrics at startup to select a shared provider.

func WithSecretManager

func WithSecretManager(secretManager SecretManager) Option

WithSecretManager supplies the manager used to resolve Redis and Sentinel password secrets.

func WithTracerProvider

func WithTracerProvider(provider trace.TracerProvider) Option

WithTracerProvider enables Redis OpenTelemetry tracing with the supplied provider.

type SecretManager

type SecretManager interface {
	Get(ctx context.Context, key string) (string, error)
}

SecretManager resolves named Redis password secrets.

Jump to

Keyboard shortcuts

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