Documentation
¶
Overview ¶
Package redis provides a cache.Cache implementation backed by a Redis server.
Wire-level: a minimal RESP2 client over net.Conn (no external deps). Connection-level: a bounded pool with configurable max size, idle timeout, and lazy connection. Operations honour the calling context's deadline by setting Read/Write deadlines on the wire.
Supported commands cover the cache-relevant subset:
GET, SET (with EX/PX/NX/XX), DEL, EXISTS, TTL/PTTL, PING, MGET, MSET, INCR/DECR, EXPIRE, FLUSHDB, SELECT, AUTH
For richer Redis usage (pub/sub, streams, transactions, scripts, cluster mode, sentinel), reach for a full client like github.com/redis/go-redis/v9 — this package's scope is the cache.Cache contract plus a few utility commands.
Index ¶
- Variables
- type Cache
- func (c *Cache) Close() error
- func (c *Cache) Delete(ctx context.Context, keys ...string) (int, error)
- func (c *Cache) Exists(ctx context.Context, key string) (bool, error)
- func (c *Cache) Get(ctx context.Context, key string) ([]byte, error)
- func (c *Cache) GetMulti(ctx context.Context, keys ...string) (map[string][]byte, error)
- func (c *Cache) Ping(ctx context.Context) error
- func (c *Cache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- func (c *Cache) SetMulti(ctx context.Context, items map[string][]byte, ttl time.Duration) error
- func (c *Cache) Stats() PoolStats
- func (c *Cache) TTL(ctx context.Context, key string) (time.Duration, error)
- type Credentials
- type CredentialsProvider
- type Options
- type PoolStats
Constants ¶
This section is empty.
Variables ¶
var ErrProtocol = errors.New("redis: protocol error")
ErrProtocol is wrapped by every malformed-reply error. errors.Is against it succeeds.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache is the Redis-backed cache.Cache implementation.
func New ¶
New creates a Cache. The first connection is established lazily on the first call (Ping forces it for eager warm-up). If MinIdleConns is set, a background goroutine pre-dials those connections.
func (*Cache) Close ¶
Close releases pooled connections, waiting up to ShutdownTimeout for in-flight operations to finish first.
type Credentials ¶
Credentials is what a CredentialsProvider yields when a new connection authenticates. Both fields are optional:
- Empty Password skips AUTH altogether (Redis without requirepass).
- Empty Username with a non-empty Password sends the legacy single-argument AUTH (compatible with Redis < 6).
- Both non-empty sends the ACL form: AUTH <user> <pass>.
type CredentialsProvider ¶
type CredentialsProvider func(ctx context.Context) (Credentials, error)
CredentialsProvider returns fresh credentials each time a new connection authenticates. Use it to integrate short-lived auth tokens — AWS ElastiCache IAM, Azure AAD, OIDC, HashiCorp Vault leases — that need refresh between dials.
The provider is called once per *new* connection (not once per command), and the context passed in is the caller's request context so providers can honour deadlines and cancellation.
If the provider returns an error the dial fails with that error wrapped; the connection is never added to the pool.
func StaticCredentials ¶
func StaticCredentials(username, password string) CredentialsProvider
StaticCredentials returns a CredentialsProvider that always yields the same (username, password) pair. Equivalent to setting Options.Username / Options.Password.
type Options ¶
type Options struct {
// Addr is the host:port of the server. Default "127.0.0.1:6379".
Addr string
// Credentials is the primary auth path. If non-nil it overrides
// Username / Password and is called once per new connection,
// receiving the caller's context. Use it for short-lived tokens
// (IAM / OIDC / Vault leases) that need refresh.
Credentials CredentialsProvider
// Password is the static-credentials shorthand. Used only when
// Credentials is nil. Empty means no AUTH.
Password string
// Username pairs with Password as the static-credentials
// shorthand (Redis 6+ ACL). Used only when Credentials is nil.
// Empty falls back to the legacy single-arg AUTH form.
Username string
// TLS, if non-nil, enables TLS for new connections. Ignored when
// Dialer is set (the custom Dialer is responsible for its own
// transport encryption).
TLS *tls.Config
// DB is the database index to SELECT on connect (0..15 typically).
DB int
// ClientName is sent via CLIENT SETNAME on connect so the
// connection shows up identifiable in CLIENT LIST / SLOWLOG /
// MONITOR. Default "drops".
ClientName string
// MaxConns caps the simultaneous connections. Default 10.
MaxConns int
// MinIdleConns pre-dials this many connections at startup (and
// keeps them warm best-effort). Smooths cold-start latency.
// Default 0 (lazy). Must be ≤ MaxConns.
MinIdleConns int
// IdleTimeout closes connections that have been idle this long
// before they're reused. 0 disables. Default 5 minutes.
IdleTimeout time.Duration
// MaxLifetime caps the absolute age of a connection regardless of
// idle status. Important when AUTH tokens rotate or a load
// balancer wants to drain connections. 0 disables. Default 0.
MaxLifetime time.Duration
// DialTimeout caps a single TCP+TLS+AUTH+SELECT+SETNAME dance.
// Default 5s.
DialTimeout time.Duration
// ReadTimeout / WriteTimeout cap per-command I/O when the
// caller's context has no deadline. Without these a misbehaving
// server could hang the goroutine indefinitely. Default 3s each.
// Set to a negative value to disable.
ReadTimeout time.Duration
WriteTimeout time.Duration
// MaxRetries is the number of retry attempts on a transient
// transport error (broken pipe, EOF, network timeout, protocol
// error). App-level errors (-ERR replies) are never retried.
// Default 1.
MaxRetries int
// ShutdownTimeout caps how long Close waits for in-flight
// operations to drain before forcing socket closure. Default 5s.
ShutdownTimeout time.Duration
// Dialer overrides the net.Dialer used for new connections. When
// set, the TLS option is ignored.
Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
// Hook fires after every operation. Compose with drops.LoggerHook
// for instant request logging.
Hook drops.Hook
// KeyPrefix is prepended to every key. Useful for multi-tenant
// deployments sharing a Redis instance.
KeyPrefix string
}
Options configures a Redis cache.
Zero-valued numeric fields take sensible production defaults (see New); explicitly set them when the defaults don't fit.
func ParseURL ¶
ParseURL parses a Redis connection URL and returns the Options it implies. The shapes accepted are:
redis://[user:password@]host[:port][/db] rediss://[user:password@]host[:port][/db]
Only host is required. Defaults: port 6379, db 0, no auth, no TLS. The "rediss" scheme enables TLS with a config that asserts the remote ServerName matches the URL host — set Options.TLS afterwards for finer control (custom root CAs, mTLS).
Anything else in the URL — query parameters, fragments, paths beyond the db segment — is ignored to keep the surface small and the parser predictable.
type PoolStats ¶
type PoolStats struct {
// TotalConns is the number of open connections (idle + checked
// out) at the moment of the snapshot.
TotalConns int
// Hits is the count of Get-from-pool calls that found a warm
// connection ready to reuse.
Hits int64
// Misses is the count of Get-from-pool calls that had to dial a
// new connection (or replaced a stale one).
Misses int64
// Timeouts is the count of Get-from-pool calls that returned
// ctx.Err() while waiting for a slot.
Timeouts int64
// StaleClosed is the count of connections closed because they
// exceeded IdleTimeout or MaxLifetime.
StaleClosed int64
// WaitCount is the count of Get-from-pool calls that had to
// wait > 0 for a slot (i.e. the pool was at capacity).
WaitCount int64
// WaitDuration is the total time spent waiting for pool slots.
WaitDuration time.Duration
// Retries is the count of transient errors that triggered a
// retry attempt.
Retries int64
}
PoolStats is a snapshot of pool / wire activity counters. All counters are monotonically increasing across the Cache's lifetime and are safe to read concurrently.