redis

package
v0.0.21 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package redis provides a Redis-backed cache implementation with singleflight support.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

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

Cache wraps go-redis with singleflight for cache stampede prevention. Implements interfaces.ByteCache by absorbing all errors internally per FailureMode. Extended methods (GetOrLoad, Ping, Client) are available on the concrete type.

func New

func New(cfg *Config) *Cache

New creates a Redis-backed cache with the given configuration. Errors from Redis operations are absorbed internally per FailureMode.

func (*Cache) Client

func (c *Cache) Client() *redis.Client

Client returns the underlying Redis client for metrics/health checks. This is an extended method available only on the concrete *Cache type.

func (*Cache) Close

func (c *Cache) Close() error

Close closes the Redis client connection. Implements io.Closer for resource cleanup.

func (*Cache) Delete

func (c *Cache) Delete(ctx context.Context, key string)

Delete removes a key from Redis. Errors are absorbed per FailureMode (logged if Error mode, silent if Bypass mode).

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, key string) ([]byte, bool)

Get retrieves a value from Redis. Returns (value, true) on hit, (nil, false) on miss or error. Errors are absorbed per FailureMode (logged if Error mode, silent if Bypass mode).

func (*Cache) GetOrLoad

func (c *Cache) GetOrLoad(
	ctx context.Context,
	key string,
	loader func() ([]byte, error),
	ttl time.Duration,
) ([]byte, error)

GetOrLoad retrieves from cache, or on miss, calls loader exactly once (singleflight). This is an extended method available only on the concrete *Cache type, not through ByteCache. Returns the loaded value and any error from the loader function.

func (*Cache) InvalidateAll

func (c *Cache) InvalidateAll(ctx context.Context) error

InvalidateAll clears the cache's Redis database (FLUSHDB). It completes the CacheInvalidator contract; the user-context invalidation feature never calls it (it would clear unrelated keys on a shared Redis).

func (*Cache) InvalidatePrefix

func (c *Cache) InvalidatePrefix(ctx context.Context, prefix string) error

InvalidatePrefix removes every key whose name begins with prefix, using a non-blocking SCAN + UNLINK sweep (UNLINK reclaims memory asynchronously). Glob metacharacters in prefix are escaped so the match stays literal. An empty or whitespace-only prefix is a guarded no-op — it never flushes the cache. Unlike the ByteCache methods, this returns its error (the CacheInvalidator contract) so a caller can retry; the error is tagged Unavailable so a consumer can treat it as transient.

func (*Cache) Liveness

func (c *Cache) Liveness(_ context.Context) error

Liveness reports whether the cache holds a connection pool (a lightweight self-check that does not touch Redis).

func (*Cache) Ping

func (c *Cache) Ping(ctx context.Context) error

Ping checks the Redis connection. This is an extended method available only on the concrete *Cache type.

func (*Cache) Readiness

func (c *Cache) Readiness(ctx context.Context) error

Readiness verifies Redis can serve traffic (a Ping).

func (*Cache) Set

func (c *Cache) Set(ctx context.Context, key string, value []byte, ttl time.Duration)

Set stores a value in Redis with the given TTL. Errors are absorbed per FailureMode (logged if Error mode, silent if Bypass mode).

func (*Cache) Start

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

Start verifies the Redis connection is reachable. The connection pool is created in New; Start pings so an unreachable Redis fails fast at the composition root rather than on the first cache operation.

func (*Cache) Stop

func (c *Cache) Stop(_ context.Context) error

Stop closes the Redis connection pool.

type Config

type Config struct {
	// Logger is the structured logger for error logging when FailureMode is
	// Error. If nil, error logging is silently skipped regardless of
	// FailureMode.
	Logger interfaces.Logger

	// Addr is the Redis server address in host:port format.
	Addr string

	// Password is the Redis authentication password. Empty means no auth.
	Password string

	// DB is the Redis database number to select after connecting.
	DB int

	// PoolSize is the maximum number of connections in the pool.
	PoolSize int

	// MinIdleConns is the minimum number of idle connections kept open.
	MinIdleConns int

	// DefaultTTL is the expiration applied when callers pass zero to Set.
	DefaultTTL time.Duration

	// OpTimeout is the maximum duration for a single Redis operation (Get,
	// Set, Delete). When non-zero, each operation gets its own context
	// deadline so a slow or unreachable Redis doesn't consume the caller's
	// entire timeout budget. Zero means no per-operation timeout (inherit
	// caller's context).
	OpTimeout time.Duration

	// FailureMode controls whether cache errors are logged (Error) or silently
	// absorbed (Bypass).
	FailureMode FailureMode

	// TLS enables an encrypted (rediss://) connection. Managed Redis such as
	// AWS ElastiCache with an auth token requires in-transit encryption, so a
	// plaintext client would hang and i/o-timeout. Its certificate is issued
	// by a public CA, so standard verification (ServerName from Addr) applies;
	// no custom root or InsecureSkipVerify is needed. Off for local dev Redis.
	TLS bool
}

Config holds Redis connection and behavior settings. Pool size defaults to 10 * GOMAXPROCS for throughput. DefaultTTL applies when callers pass zero to Set.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults for Redis configuration.

type FailureMode

type FailureMode int

FailureMode determines how cache errors are handled by the cache adapter. In bypass mode, cache errors are swallowed and treated as misses. In error mode, cache errors are logged but still absorbed (since ByteCache cannot return errors).

const (
	// FailureModeBypass silently absorbs cache errors (treats as miss).
	FailureModeBypass FailureMode = iota

	// FailureModeError logs cache errors but still absorbs them (ByteCache
	// contract).
	FailureModeError
)

Jump to

Keyboard shortcuts

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