redis

package
v0.0.0-...-252e742 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package redis provides the Redis client singleton and shared utilities for hash, set, and transaction operations.

This file contains the Redis client singleton — the single point of configuration and connection management for the entire application.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddHook

func AddHook(hook Hook)

AddHook attaches a Hook to the shared client for observability. Must be called after Init.

func Client

func Client() *redis.Client

Client returns the shared Redis client. Panics if Init has not been called.

func Close

func Close()

Close shuts down the shared Redis client and releases all pool connections. After Close, Client() and Eval() will panic. Safe to call multiple times. After Close, Init() can be called again to reinitialize.

func Conn

func Conn() *redis.Conn

func Eval

func Eval(ctx context.Context, id scripts.ID, keys []string, args ...interface{}) (interface{}, error)

Eval executes a pre-registered Lua script by ID. Uses the cached SHA for efficiency; falls back to EVAL on NOSCRIPT errors.

func Init

func Init(ctx context.Context, cfg Config) error

Init creates the shared Redis client, verifies connectivity, and loads all Lua scripts into Redis. Safe to call multiple times; returns immediately if already initialized. If a previous call failed, retries initialization. Panics if addr is empty.

func Int64

func Int64(reply interface{}) (int64, error)

Int64 extracts an int64 from a Redis Lua script reply. Returns an error if the reply is not an int64.

func LoadHash

func LoadHash(ctx context.Context, key string, entity string) (map[string]string, error)

LoadHash wraps HGetAll with standard error handling. Returns an error if the hash is empty or the Redis operation fails.

Example:

hash, err := redis.LoadHash(ctx, key, "queue properties")

func LoadHashField

func LoadHashField(ctx context.Context, key, field, entity string) (string, error)

LoadHashField reads a single field from a Redis hash. Returns an error if the field doesn't exist or the Redis operation fails.

Example:

value, err := redis.LoadHashField(ctx, key, "status", "message status")

func LoadSetMembers

func LoadSetMembers(ctx context.Context, key string, entity string) ([]string, error)

LoadSetMembers wraps SMembers with standard error handling. Returns an empty slice if the set has no members.

Example:

members, err := redis.LoadSetMembers(ctx, key, "all exchanges")

func SetContains

func SetContains(ctx context.Context, key, value, entity string) (bool, error)

SetContains checks if a value exists in a Redis set.

Example:

exists, err := redis.SetContains(ctx, key, value, "exchange index")

func Slice

func Slice(reply interface{}) ([]interface{}, error)

Slice extracts a []interface{} from a Redis Lua script reply. Returns an error if the reply is not a slice.

func Stats

func Stats() *redis.PoolStats

Stats returns connection pool statistics for health checks and monitoring.

func String

func String(reply interface{}) (string, error)

String extracts a string from a Redis Lua script reply. Returns an error if the reply is not a string.

func WithTransaction

func WithTransaction(ctx context.Context, watchKeys []string, maxAttempts int, fn func(*redis.Tx) error) error

WithTransaction executes a function within a Redis transaction with retries. Automatically retries on optimistic lock failures (TxFailedErr).

The function receives a *redis.Tx that can be used to read watched keys and build a pipeline of commands to execute atomically.

Example:

err := redis.WithTransaction(ctx, watchKeys, 3, func(tx *redis.Tx) error {
    // Read values under WATCH
    val, err := tx.Get(ctx, key).Result()
    if err != nil {
        return err
    }

    // Execute writes atomically
    _, err = tx.TxPipelined(ctx, func(pipe redis.Pipeliner) error {
        pipe.Set(ctx, key, newVal, 0)
        return nil
    })
    return err
})

Types

type Config

type Config struct {
	// Addr is the Redis server address (required).
	Addr string

	// Password is the Redis password.
	Password string

	// DB is the Redis database number.
	DB int

	// PoolSize is the maximum number of connections (default: 10 * GOMAXPROCS).
	PoolSize int

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

	// ConnMaxIdleTime is the maximum idle time for a connection (default: 30m).
	ConnMaxIdleTime time.Duration

	// ConnMaxLifetime is the maximum age of a connection (default: 0 = forever).
	ConnMaxLifetime time.Duration

	// PoolTimeout is the amount of time to wait for a connection when pool is exhausted.
	PoolTimeout time.Duration
}

Config controls the Redis client and its internal connection pool. Zero values use go-redis defaults.

type Hook

type Hook interface {
	redis.Hook
}

Hook is a callback interface for observing or intercepting Redis commands. Use it for logging, metrics, or tracing.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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