redis

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package redis provides functionality for interacting with Redis.

The redis package offers a simplified interface for working with Redis key-value store, providing connection management, caching operations, pub/sub capabilities, and advanced data structure operations with a focus on reliability and ease of use.

Core Features:

  • Robust connection management with automatic reconnection
  • Connection pooling for optimal performance
  • Simple key-value operations (Get, Set, Delete)
  • Advanced data structures (Lists, Sets, Sorted Sets, Hashes)
  • Pub/Sub messaging support
  • Pipeline and transaction support
  • TTL and expiration management
  • Integration with the Logger package for structured logging
  • TLS/SSL support for secure connections
  • Cluster and Sentinel support

Basic Usage:

import (
	"github.com/Aleph-Alpha/std/v1/redis"
	"github.com/Aleph-Alpha/std/v1/logger"
	"context"
	"time"
)

// Create a new Redis client
client, err := redis.NewClient(redis.Config{
	Host:     "localhost",
	Port:     6379,
	Password: "",
	DB:       0,
})
if err != nil {
	log.Fatal("Failed to connect to Redis", err, nil)
}
defer client.Close()

// Set a value with TTL
ctx := context.Background()
err = client.Set(ctx, "user:123", "John Doe", 5*time.Minute)
if err != nil {
	log.Error("Failed to set value", err, nil)
}

// Get a value
value, err := client.Get(ctx, "user:123")
if err != nil {
	log.Error("Failed to get value", err, nil)
}
fmt.Println("User:", value)

// Delete a key
err = client.Delete(ctx, "user:123")
if err != nil {
	log.Error("Failed to delete key", err, nil)
}

Hash Operations:

// Set hash fields
err = client.HSet(ctx, "user:123", map[string]interface{}{
	"name":  "John Doe",
	"email": "john@example.com",
	"age":   30,
})

// Get a single hash field
name, err := client.HGet(ctx, "user:123", "name")

// Get all hash fields
user, err := client.HGetAll(ctx, "user:123")

// Delete hash fields
err = client.HDel(ctx, "user:123", "age")

List Operations:

// Push to list (left/right)
err = client.LPush(ctx, "tasks", "task1", "task2")
err = client.RPush(ctx, "tasks", "task3")

// Pop from list
task, err := client.LPop(ctx, "tasks")
task, err := client.RPop(ctx, "tasks")

// Get list range
tasks, err := client.LRange(ctx, "tasks", 0, -1)

// Get list length
length, err := client.LLen(ctx, "tasks")

Set Operations:

// Add members to set
err = client.SAdd(ctx, "tags", "redis", "cache", "database")

// Get all members
tags, err := client.SMembers(ctx, "tags")

// Check membership
exists, err := client.SIsMember(ctx, "tags", "redis")

// Remove members
err = client.SRem(ctx, "tags", "cache")

Sorted Set Operations:

// Add members with scores
err = client.ZAdd(ctx, "leaderboard", map[string]float64{
	"player1": 100,
	"player2": 200,
	"player3": 150,
})

// Get range by rank
players, err := client.ZRange(ctx, "leaderboard", 0, -1)

// Get range by score
players, err := client.ZRangeByScore(ctx, "leaderboard", 100, 200)

// Get member score
score, err := client.ZScore(ctx, "leaderboard", "player1")

Pub/Sub Messaging:

// Publisher
err = client.Publish(ctx, "events", "user.created")

// Subscriber
pubsub := client.Subscribe(ctx, "events")
defer pubsub.Close()

for msg := range pubsub.Channel() {
	fmt.Println("Received:", msg.Channel, msg.Payload)
}

Pattern-based Subscription:

// Subscribe to pattern
pubsub := client.PSubscribe(ctx, "user.*")
defer pubsub.Close()

for msg := range pubsub.Channel() {
	fmt.Println("Received on pattern:", msg.Channel, msg.Payload)
}

Pipeline for Bulk Operations:

// Create pipeline
pipe := client.Pipeline()

// Queue multiple commands
pipe.Set(ctx, "key1", "value1", 0)
pipe.Set(ctx, "key2", "value2", 0)
pipe.Incr(ctx, "counter")

// Execute all commands at once
_, err := pipe.Exec(ctx)
if err != nil {
	log.Error("Pipeline failed", err, nil)
}

Transactions (MULTI/EXEC):

// Watch keys for optimistic locking
err = client.Watch(ctx, func(tx *redis.Tx) error {
	// Get current value
	val, err := tx.Get(ctx, "counter").Int()
	if err != nil && err != redis.Nil {
		return err
	}

	// Start transaction
	_, err = tx.TxPipelined(ctx, func(pipe redis.Pipeliner) error {
		pipe.Set(ctx, "counter", val+1, 0)
		return nil
	})
	return err
}, "counter")

TTL and Expiration:

// Set expiration on existing key
err = client.Expire(ctx, "session:123", 30*time.Minute)

// Get TTL
ttl, err := client.TTL(ctx, "session:123")

// Persist (remove expiration)
err = client.Persist(ctx, "session:123")

Key Scanning:

// Scan keys with pattern
keys, err := client.Keys(ctx, "user:*")

// Scan with cursor (for large datasets)
iter := client.Scan(ctx, 0, "user:*", 100)
for iter.Next(ctx) {
	key := iter.Val()
	fmt.Println("Key:", key)
}
if err := iter.Err(); err != nil {
	log.Error("Scan error", err, nil)
}

JSON Operations (with RedisJSON module):

// Set JSON value
user := map[string]interface{}{
	"name":  "John",
	"email": "john@example.com",
	"age":   30,
}
err = client.JSONSet(ctx, "user:123", "$", user)

// Get JSON value
var result map[string]interface{}
err = client.JSONGet(ctx, "user:123", &result, "$")

// Update JSON field
err = client.JSONSet(ctx, "user:123", "$.age", 31)

Distributed Locking:

// Acquire lock
lock, err := client.AcquireLock(ctx, "resource:123", 10*time.Second)
if err != nil {
	log.Error("Failed to acquire lock", err, nil)
	return
}
defer lock.Release(ctx)

// Do work with exclusive access
// ...

FX Module Integration:

This package provides a fx module for easy integration:

app := fx.New(
	logger.FXModule, // Optional: provides std logger
	redis.FXModule,
	// ... other modules
)
app.Run()

The Redis module will automatically use the logger if it's available in the dependency injection container.

Configuration:

The redis client can be configured via environment variables or explicitly:

REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=secret
REDIS_DB=0
REDIS_POOL_SIZE=10

Custom Logger Integration:

You can integrate the std/v1/logger for better error logging:

import (
	"github.com/Aleph-Alpha/std/v1/logger"
	"github.com/Aleph-Alpha/std/v1/redis"
)

// Create logger
log := logger.NewLoggerClient(logger.Config{
	Level:       logger.Info,
	ServiceName: "my-service",
})

// Create Redis client with logger
client, err := redis.NewClient(redis.Config{
	Host:     "localhost",
	Port:     6379,
	Logger:   log, // Redis errors will use this logger
})

TLS/SSL Configuration:

client, err := redis.NewClient(redis.Config{
	Host:     "redis.example.com",
	Port:     6380,
	TLS: redis.TLSConfig{
		Enabled:            true,
		CACertPath:         "/path/to/ca.crt",
		ClientCertPath:     "/path/to/client.crt",
		ClientKeyPath:      "/path/to/client.key",
		InsecureSkipVerify: false,
	},
})

Cluster Configuration:

client, err := redis.NewClusterClient(redis.ClusterConfig{
	Addrs: []string{
		"localhost:7000",
		"localhost:7001",
		"localhost:7002",
	},
	Password: "secret",
	TLS:      tlsConfig,
})

Sentinel Configuration:

client, err := redis.NewFailoverClient(redis.FailoverConfig{
	MasterName: "mymaster",
	SentinelAddrs: []string{
		"localhost:26379",
		"localhost:26380",
		"localhost:26381",
	},
	Password: "secret",
	DB:       0,
})

Connection Pooling:

The Redis client uses connection pooling by default for optimal performance:

client, err := redis.NewClient(redis.Config{
	Host:         "localhost",
	Port:         6379,
	PoolSize:     10,                // Maximum number of connections
	MinIdleConns: 5,                 // Minimum idle connections
	MaxConnAge:   30 * time.Minute,  // Maximum connection age
	PoolTimeout:  4 * time.Second,   // Timeout when getting connection
	IdleTimeout:  5 * time.Minute,   // Close idle connections after timeout
})

Health Check:

// Ping to check connection
err := client.Ping(ctx)
if err != nil {
	log.Error("Redis is not healthy", err, nil)
}

// Get connection pool stats
stats := client.PoolStats()
fmt.Printf("Hits: %d, Misses: %d, Timeouts: %d\n",
	stats.Hits, stats.Misses, stats.Timeouts)

Caching Pattern with Automatic Serialization:

type User struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

// Set with automatic JSON serialization
user := User{ID: 123, Name: "John", Email: "john@example.com"}
err := client.SetJSON(ctx, "user:123", user, 10*time.Minute)

// Get with automatic JSON deserialization
var cachedUser User
err = client.GetJSON(ctx, "user:123", &cachedUser)
if err == redis.Nil {
	// Cache miss - fetch from database
	cachedUser = fetchUserFromDB(123)
	client.SetJSON(ctx, "user:123", cachedUser, 10*time.Minute)
}

Rate Limiting:

// Simple rate limiter using Redis
allowed, err := client.RateLimit(ctx, "api:user:123", 100, time.Minute)
if err != nil {
	log.Error("Rate limit check failed", err, nil)
}
if !allowed {
	return errors.New("rate limit exceeded")
}

Thread Safety:

All methods on the Redis client are safe for concurrent use by multiple goroutines. The underlying connection pool handles concurrent access efficiently.

Index

Constants

View Source
const (
	DefaultHost                = "localhost"
	DefaultPort                = 6379
	DefaultDB                  = 0
	DefaultPoolSize            = 0 // 10 per CPU (set by redis client)
	DefaultMinIdleConns        = 0
	DefaultMaxConnAge          = 0
	DefaultPoolTimeout         = 0 // ReadTimeout + 1 second (set by redis client)
	DefaultIdleTimeout         = 5 * time.Minute
	DefaultIdleCheckFrequency  = 1 * time.Minute
	DefaultMaxRetries          = 3
	DefaultMinRetryBackoff     = 8 * time.Millisecond
	DefaultMaxRetryBackoff     = 512 * time.Millisecond
	DefaultDialTimeout         = 5 * time.Second
	DefaultReadTimeout         = 3 * time.Second
	DefaultWriteTimeout        = 0 // ReadTimeout (set by redis client)
	DefaultClusterMaxRedirects = 3
)

Default values for configuration

Variables

View Source
var (
	// Nil is returned when a key does not exist.
	Nil = errors.New("redis: nil")

	// ErrClosed is returned when the client is closed.
	ErrClosed = errors.New("redis: client is closed")

	// ErrPoolTimeout is returned when all connections in the pool are busy
	// and PoolTimeout was reached.
	ErrPoolTimeout = errors.New("redis: connection pool timeout")

	// ErrLockNotAcquired is returned when a lock cannot be acquired.
	ErrLockNotAcquired = errors.New("redis: lock not acquired")

	// ErrLockNotHeld is returned when trying to release a lock that is not held.
	ErrLockNotHeld = errors.New("redis: lock not held")

	// ErrRateLimitExceeded is returned when a rate limit is exceeded.
	ErrRateLimitExceeded = errors.New("redis: rate limit exceeded")
)

Common Redis errors

View Source
var ClusterFXModule = fx.Module("redis-cluster",
	fx.Provide(
		NewClusterClientWithDI,
	),
	fx.Invoke(RegisterRedisLifecycle),
)

ClusterFXModule is an fx.Module for Redis Cluster configuration.

FXModule is an fx.Module that provides and configures the Redis client. This module registers the Redis client with the Fx dependency injection framework, making it available to other components in the application.

The module: 1. Provides the Redis client factory function 2. Invokes the lifecycle registration to manage the client's lifecycle

Usage:

app := fx.New(
    redis.FXModule,
    // other modules...
)
View Source
var FailoverFXModule = fx.Module("redis-failover",
	fx.Provide(
		NewFailoverClientWithDI,
	),
	fx.Invoke(RegisterRedisLifecycle),
)

FailoverFXModule is an fx.Module for Redis Sentinel (failover) configuration.

Functions

func IsClosedError

func IsClosedError(err error) bool

IsClosedError checks if the error is a "client is closed" error.

func IsNilError

func IsNilError(err error) bool

IsNilError checks if the error is a "key does not exist" error.

func IsPoolTimeoutError

func IsPoolTimeoutError(err error) bool

IsPoolTimeoutError checks if the error is a pool timeout error.

func RegisterRedisLifecycle

func RegisterRedisLifecycle(params RedisLifecycleParams)

RegisterRedisLifecycle registers the Redis client with the fx lifecycle system. This function sets up proper initialization and graceful shutdown of the Redis client.

Parameters:

  • params: The lifecycle parameters containing the Redis client

The function:

  1. On application start: Pings Redis to ensure the connection is healthy
  2. On application stop: Triggers a graceful shutdown of the Redis client, closing connections cleanly.

This ensures that the Redis client remains available throughout the application's lifetime and is properly cleaned up during shutdown.

Types

type ClusterConfig

type ClusterConfig struct {
	// Addrs is a seed list of cluster nodes
	// Example: []string{"localhost:7000", "localhost:7001", "localhost:7002"}
	Addrs []string

	// Username is the Redis username for ACL authentication (Redis 6.0+)
	Username string

	// Password is the Redis password for authentication
	Password string

	// MaxRedirects is the maximum number of retries for MOVED/ASK redirects
	// Default: 3
	MaxRedirects int

	// ReadOnly enables read-only mode (read from replicas)
	// Default: false
	ReadOnly bool

	// RouteByLatency enables routing read-only commands to the closest master or replica node
	// Default: false
	RouteByLatency bool

	// RouteRandomly enables routing read-only commands to random master or replica nodes
	// Default: false
	RouteRandomly bool

	// PoolSize is the maximum number of socket connections per node
	// Default: 10 per CPU
	PoolSize int

	// MinIdleConns is the minimum number of idle connections per node
	// Default: 0
	MinIdleConns int

	// MaxConnAge is the maximum duration a connection can be reused
	// Default: 0 (no maximum age)
	MaxConnAge time.Duration

	// PoolTimeout is the amount of time to wait for a connection from the pool
	// Default: ReadTimeout + 1 second
	PoolTimeout time.Duration

	// IdleTimeout is the amount of time after which idle connections are closed
	// Default: 5 minutes
	IdleTimeout time.Duration

	// MaxRetries is the maximum number of retries before giving up
	// Default: 3
	MaxRetries int

	// MinRetryBackoff is the minimum backoff between each retry
	// Default: 8 milliseconds
	MinRetryBackoff time.Duration

	// MaxRetryBackoff is the maximum backoff between each retry
	// Default: 512 milliseconds
	MaxRetryBackoff time.Duration

	// DialTimeout is the timeout for establishing new connections
	// Default: 5 seconds
	DialTimeout time.Duration

	// ReadTimeout is the timeout for socket reads
	// Default: 3 seconds
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for socket writes
	// Default: ReadTimeout
	WriteTimeout time.Duration

	// TLS contains TLS/SSL configuration
	TLS TLSConfig

	// Logger is an optional logger from std/v1/logger package
	Logger Logger
}

ClusterConfig defines the configuration for Redis Cluster mode. Use this when connecting to a Redis Cluster deployment.

type ClusterRedisParams

type ClusterRedisParams struct {
	fx.In

	Config ClusterConfig
	Logger Logger `optional:"true"`
}

ClusterRedisParams groups the dependencies needed to create a Redis Cluster client

type Config

type Config struct {
	// Host is the Redis server hostname or IP address
	// Default: "localhost"
	Host string

	// Port is the Redis server port
	// Default: 6379
	Port int

	// Username is the Redis username for ACL authentication (Redis 6.0+)
	// Leave empty for no username-based authentication
	Username string

	// Password is the Redis password for authentication
	// Leave empty for no authentication
	Password string

	// DB is the Redis database number to use (0-15 by default)
	// Default: 0
	DB int

	// PoolSize is the maximum number of socket connections
	// Default: 10 per CPU
	PoolSize int

	// MinIdleConns is the minimum number of idle connections to maintain
	// Default: 0 (no minimum)
	MinIdleConns int

	// MaxConnAge is the maximum duration a connection can be reused
	// Connections older than this will be closed and new ones created
	// Default: 0 (no maximum age)
	MaxConnAge time.Duration

	// PoolTimeout is the amount of time to wait for a connection from the pool
	// Default: ReadTimeout + 1 second
	PoolTimeout time.Duration

	// IdleTimeout is the amount of time after which idle connections are closed
	// Default: 5 minutes
	IdleTimeout time.Duration

	// IdleCheckFrequency is how often to check for idle connections to close
	// Default: 1 minute
	IdleCheckFrequency time.Duration

	// MaxRetries is the maximum number of retries before giving up
	// Default: 3
	// Set to -1 to disable retries
	MaxRetries int

	// MinRetryBackoff is the minimum backoff between each retry
	// Default: 8 milliseconds
	MinRetryBackoff time.Duration

	// MaxRetryBackoff is the maximum backoff between each retry
	// Default: 512 milliseconds
	MaxRetryBackoff time.Duration

	// DialTimeout is the timeout for establishing new connections
	// Default: 5 seconds
	DialTimeout time.Duration

	// ReadTimeout is the timeout for socket reads
	// If reached, commands will fail with a timeout instead of blocking
	// Default: 3 seconds
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for socket writes
	// If reached, commands will fail with a timeout instead of blocking
	// Default: ReadTimeout
	WriteTimeout time.Duration

	// TLS contains TLS/SSL configuration
	TLS TLSConfig

	// Logger is an optional logger from std/v1/logger package
	// If provided, it will be used for Redis error logging
	Logger Logger
}

Config defines the top-level configuration structure for the Redis client. It contains all the necessary configuration sections for establishing connections, setting up connection pooling, and configuring TLS/SSL.

type FailoverConfig

type FailoverConfig struct {
	// MasterName is the name of the master instance as configured in Sentinel
	MasterName string

	// SentinelAddrs is a list of Sentinel node addresses
	// Example: []string{"localhost:26379", "localhost:26380", "localhost:26381"}
	SentinelAddrs []string

	// SentinelUsername is the username for Sentinel authentication (Redis 6.0+)
	SentinelUsername string

	// SentinelPassword is the password for Sentinel authentication
	SentinelPassword string

	// Username is the Redis username for ACL authentication (Redis 6.0+)
	Username string

	// Password is the Redis password for authentication
	Password string

	// DB is the Redis database number to use
	// Default: 0
	DB int

	// ReplicaOnly forces read-only queries to go to replica nodes
	// Default: false
	ReplicaOnly bool

	// UseDisconnectedReplicas allows using replicas that are disconnected from master
	// Default: false
	UseDisconnectedReplicas bool

	// PoolSize is the maximum number of socket connections
	// Default: 10 per CPU
	PoolSize int

	// MinIdleConns is the minimum number of idle connections
	// Default: 0
	MinIdleConns int

	// MaxConnAge is the maximum duration a connection can be reused
	// Default: 0 (no maximum age)
	MaxConnAge time.Duration

	// PoolTimeout is the amount of time to wait for a connection from the pool
	// Default: ReadTimeout + 1 second
	PoolTimeout time.Duration

	// IdleTimeout is the amount of time after which idle connections are closed
	// Default: 5 minutes
	IdleTimeout time.Duration

	// MaxRetries is the maximum number of retries before giving up
	// Default: 3
	MaxRetries int

	// MinRetryBackoff is the minimum backoff between each retry
	// Default: 8 milliseconds
	MinRetryBackoff time.Duration

	// MaxRetryBackoff is the maximum backoff between each retry
	// Default: 512 milliseconds
	MaxRetryBackoff time.Duration

	// DialTimeout is the timeout for establishing new connections
	// Default: 5 seconds
	DialTimeout time.Duration

	// ReadTimeout is the timeout for socket reads
	// Default: 3 seconds
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for socket writes
	// Default: ReadTimeout
	WriteTimeout time.Duration

	// TLS contains TLS/SSL configuration
	TLS TLSConfig

	// Logger is an optional logger from std/v1/logger package
	Logger Logger
}

FailoverConfig defines the configuration for Redis Sentinel (failover) mode. Use this when connecting to a Redis Sentinel setup for high availability.

type FailoverRedisParams

type FailoverRedisParams struct {
	fx.In

	Config FailoverConfig
	Logger Logger `optional:"true"`
}

FailoverRedisParams groups the dependencies needed to create a Redis Sentinel client

type Lock

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

Lock represents a distributed lock.

func (*Lock) Refresh

func (l *Lock) Refresh(ctx context.Context) error

Refresh extends the TTL of the lock.

func (*Lock) Release

func (l *Lock) Release(ctx context.Context) error

Release releases the distributed lock.

type Logger

type Logger interface {
	Error(msg string, err error, fields ...map[string]interface{})
	Info(msg string, err error, fields ...map[string]interface{})
	Warn(msg string, err error, fields ...map[string]interface{})
}

Logger is an interface that matches the std/v1/logger.Logger

type Redis

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

Redis represents a client for interacting with Redis. It wraps the go-redis client and provides a simplified interface with connection management and helper methods.

func NewClient

func NewClient(cfg Config) (*Redis, error)

NewClient creates and initializes a new Redis client with the provided configuration. This is for connecting to a standalone Redis instance.

Parameters:

  • cfg: Configuration for connecting to Redis

Returns a new Redis client instance that is ready to use.

Example:

client, err := redis.NewClient(redis.Config{
	Host:     "localhost",
	Port:     6379,
	Password: "",
	DB:       0,
})
if err != nil {
	log.Printf("ERROR: failed to create Redis client: %v", err)
	return nil, err
}
defer client.Close()

func NewClientWithDI

func NewClientWithDI(params RedisParams) (*Redis, error)

NewClientWithDI creates a new Redis client using dependency injection. This function is designed to be used with Uber's fx dependency injection framework where dependencies are automatically provided via the RedisParams struct.

Parameters:

  • params: A RedisParams struct that contains the Config instance and optionally a Logger instance required to initialize the Redis client. This struct embeds fx.In to enable automatic injection of these dependencies.

Returns:

  • *Redis: A fully initialized Redis client ready for use.

Example usage with fx:

app := fx.New(
    redis.FXModule,
    logger.FXModule, // Optional: provides logger
    fx.Provide(
        func() redis.Config {
            return loadRedisConfig() // Your config loading function
        },
    ),
)

Under the hood, this function injects the optional logger before delegating to the standard NewClient function.

func NewClusterClient

func NewClusterClient(cfg ClusterConfig) (*Redis, error)

NewClusterClient creates and initializes a new Redis Cluster client. This is for connecting to a Redis Cluster deployment.

Parameters:

  • cfg: Configuration for connecting to Redis Cluster

Returns a new Redis client instance that is ready to use.

Example:

client, err := redis.NewClusterClient(redis.ClusterConfig{
	Addrs: []string{
		"localhost:7000",
		"localhost:7001",
		"localhost:7002",
	},
	Password: "",
})

func NewClusterClientWithDI

func NewClusterClientWithDI(params ClusterRedisParams) (*Redis, error)

NewClusterClientWithDI creates a new Redis Cluster client using dependency injection.

func NewFailoverClient

func NewFailoverClient(cfg FailoverConfig) (*Redis, error)

NewFailoverClient creates and initializes a new Redis Sentinel (failover) client. This is for connecting to a Redis Sentinel setup for high availability.

Parameters:

  • cfg: Configuration for connecting to Redis Sentinel

Returns a new Redis client instance that is ready to use.

Example:

client, err := redis.NewFailoverClient(redis.FailoverConfig{
	MasterName: "mymaster",
	SentinelAddrs: []string{
		"localhost:26379",
		"localhost:26380",
		"localhost:26381",
	},
	Password: "",
	DB:       0,
})

func NewFailoverClientWithDI

func NewFailoverClientWithDI(params FailoverRedisParams) (*Redis, error)

NewFailoverClientWithDI creates a new Redis Sentinel client using dependency injection.

func (*Redis) AcquireLock

func (r *Redis) AcquireLock(ctx context.Context, key string, ttl time.Duration) (*Lock, error)

AcquireLock attempts to acquire a distributed lock. Returns a Lock instance if successful, or an error if the lock is already held.

func (*Redis) BLPop

func (r *Redis) BLPop(ctx context.Context, timeout time.Duration, keys ...string) ([]string, error)

BLPop is a blocking version of LPop with a timeout. It blocks until an element is available or the timeout is reached.

func (*Redis) BRPop

func (r *Redis) BRPop(ctx context.Context, timeout time.Duration, keys ...string) ([]string, error)

BRPop is a blocking version of RPop with a timeout.

func (*Redis) Client

func (r *Redis) Client() redis.UniversalClient

Client returns the underlying go-redis client for advanced operations. This allows users to access the full go-redis API when needed.

func (*Redis) Close

func (r *Redis) Close() error

Close closes the Redis client and releases all resources. This should be called when the client is no longer needed.

func (*Redis) Decr

func (r *Redis) Decr(ctx context.Context, key string) (int64, error)

Decr decrements the integer value of a key by one.

func (*Redis) DecrBy

func (r *Redis) DecrBy(ctx context.Context, key string, value int64) (int64, error)

DecrBy decrements the integer value of a key by the given amount.

func (*Redis) Delete

func (r *Redis) Delete(ctx context.Context, keys ...string) (int64, error)

Delete deletes one or more keys. Returns the number of keys that were deleted.

func (*Redis) Exists

func (r *Redis) Exists(ctx context.Context, keys ...string) (int64, error)

Exists checks if one or more keys exist. Returns the number of keys that exist.

func (*Redis) Expire

func (r *Redis) Expire(ctx context.Context, key string, ttl time.Duration) (bool, error)

Expire sets a timeout on a key. After the timeout has expired, the key will be automatically deleted.

func (*Redis) ExpireAt

func (r *Redis) ExpireAt(ctx context.Context, key string, tm time.Time) (bool, error)

ExpireAt sets an expiration timestamp on a key. The key will be deleted when the timestamp is reached.

func (*Redis) Get

func (r *Redis) Get(ctx context.Context, key string) (string, error)

Get retrieves the value associated with the given key. Returns ErrNil if the key does not exist.

func (*Redis) GetJSON

func (r *Redis) GetJSON(ctx context.Context, key string, dest interface{}) error

GetJSON retrieves the value from Redis and deserializes it from JSON.

func (*Redis) GetSet

func (r *Redis) GetSet(ctx context.Context, key string, value interface{}) (string, error)

GetSet sets the value for the given key and returns the old value.

func (*Redis) HDel

func (r *Redis) HDel(ctx context.Context, key string, fields ...string) (int64, error)

HDel deletes one or more hash fields.

func (*Redis) HExists

func (r *Redis) HExists(ctx context.Context, key, field string) (bool, error)

HExists checks if a field exists in the hash stored at key.

func (*Redis) HGet

func (r *Redis) HGet(ctx context.Context, key, field string) (string, error)

HGet returns the value associated with field in the hash stored at key.

func (*Redis) HGetAll

func (r *Redis) HGetAll(ctx context.Context, key string) (map[string]string, error)

HGetAll returns all fields and values in the hash stored at key.

func (*Redis) HIncrBy

func (r *Redis) HIncrBy(ctx context.Context, key, field string, incr int64) (int64, error)

HIncrBy increments the integer value of a hash field by the given number.

func (*Redis) HIncrByFloat

func (r *Redis) HIncrByFloat(ctx context.Context, key, field string, incr float64) (float64, error)

HIncrByFloat increments the float value of a hash field by the given amount.

func (*Redis) HKeys

func (r *Redis) HKeys(ctx context.Context, key string) ([]string, error)

HKeys returns all field names in the hash stored at key.

func (*Redis) HLen

func (r *Redis) HLen(ctx context.Context, key string) (int64, error)

HLen returns the number of fields in the hash stored at key.

func (*Redis) HMGet

func (r *Redis) HMGet(ctx context.Context, key string, fields ...string) ([]interface{}, error)

HMGet returns the values associated with the specified fields in the hash.

func (*Redis) HSet

func (r *Redis) HSet(ctx context.Context, key string, values ...interface{}) (int64, error)

HSet sets field in the hash stored at key to value. If the key doesn't exist, a new hash is created.

func (*Redis) HVals

func (r *Redis) HVals(ctx context.Context, key string) ([]string, error)

HVals returns all values in the hash stored at key.

func (*Redis) Incr

func (r *Redis) Incr(ctx context.Context, key string) (int64, error)

Incr increments the integer value of a key by one. If the key does not exist, it is set to 0 before performing the operation.

func (*Redis) IncrBy

func (r *Redis) IncrBy(ctx context.Context, key string, value int64) (int64, error)

IncrBy increments the integer value of a key by the given amount.

func (*Redis) IncrByFloat

func (r *Redis) IncrByFloat(ctx context.Context, key string, value float64) (float64, error)

IncrByFloat increments the float value of a key by the given amount.

func (*Redis) Keys

func (r *Redis) Keys(ctx context.Context, pattern string) ([]string, error)

Keys returns all keys matching the given pattern. WARNING: Use with caution in production as it can be slow on large datasets. Consider using Scan instead.

func (*Redis) LIndex

func (r *Redis) LIndex(ctx context.Context, key string, index int64) (string, error)

LIndex returns the element at index in the list stored at key.

func (*Redis) LLen

func (r *Redis) LLen(ctx context.Context, key string) (int64, error)

LLen returns the length of the list stored at key.

func (*Redis) LPop

func (r *Redis) LPop(ctx context.Context, key string) (string, error)

LPop removes and returns the first element of the list stored at key.

func (*Redis) LPush

func (r *Redis) LPush(ctx context.Context, key string, values ...interface{}) (int64, error)

LPush inserts all the specified values at the head of the list stored at key.

func (*Redis) LRange

func (r *Redis) LRange(ctx context.Context, key string, start, stop int64) ([]string, error)

LRange returns the specified elements of the list stored at key. The offsets start and stop are zero-based indexes. Use -1 for the last element, -2 for the second last, etc.

func (*Redis) LRem

func (r *Redis) LRem(ctx context.Context, key string, count int64, value interface{}) (int64, error)

LRem removes the first count occurrences of elements equal to value from the list.

func (*Redis) LSet

func (r *Redis) LSet(ctx context.Context, key string, index int64, value interface{}) error

LSet sets the list element at index to value.

func (*Redis) LTrim

func (r *Redis) LTrim(ctx context.Context, key string, start, stop int64) error

LTrim trims the list to the specified range.

func (*Redis) MGet

func (r *Redis) MGet(ctx context.Context, keys ...string) ([]interface{}, error)

MGet retrieves the values of multiple keys at once. Returns a slice of values in the same order as the keys. If a key doesn't exist, its value will be nil.

func (*Redis) MSet

func (r *Redis) MSet(ctx context.Context, values ...interface{}) error

MSet sets multiple key-value pairs at once. The values parameter should be in the format: key1, value1, key2, value2, ...

func (*Redis) PSubscribe

func (r *Redis) PSubscribe(ctx context.Context, patterns ...string) *redis.PubSub

PSubscribe subscribes to channels matching the given patterns.

func (*Redis) Persist

func (r *Redis) Persist(ctx context.Context, key string) (bool, error)

Persist removes the expiration from a key.

func (*Redis) Ping

func (r *Redis) Ping(ctx context.Context) error

Ping checks if the Redis server is reachable and responsive. It returns an error if the connection fails.

func (*Redis) Pipeline

func (r *Redis) Pipeline() redis.Pipeliner

Pipeline returns a new pipeline. Pipelines allow sending multiple commands in a single request.

func (*Redis) PoolStats

func (r *Redis) PoolStats() *redis.PoolStats

PoolStats returns connection pool statistics. Useful for monitoring connection pool health.

func (*Redis) Publish

func (r *Redis) Publish(ctx context.Context, channel string, message interface{}) (int64, error)

Publish posts a message to the given channel. Returns the number of clients that received the message.

func (*Redis) RPop

func (r *Redis) RPop(ctx context.Context, key string) (string, error)

RPop removes and returns the last element of the list stored at key.

func (*Redis) RPush

func (r *Redis) RPush(ctx context.Context, key string, values ...interface{}) (int64, error)

RPush inserts all the specified values at the tail of the list stored at key.

func (*Redis) RateLimit

func (r *Redis) RateLimit(ctx context.Context, key string, limit int64, window time.Duration) (bool, error)

RateLimit implements a simple rate limiter using Redis. Returns true if the operation is allowed, false if rate limit is exceeded.

func (*Redis) SAdd

func (r *Redis) SAdd(ctx context.Context, key string, members ...interface{}) (int64, error)

SAdd adds the specified members to the set stored at key.

func (*Redis) SCard

func (r *Redis) SCard(ctx context.Context, key string) (int64, error)

SCard returns the number of elements in the set stored at key.

func (*Redis) SDiff

func (r *Redis) SDiff(ctx context.Context, keys ...string) ([]string, error)

SDiff returns the members of the set resulting from the difference between the first set and all the successive sets.

func (*Redis) SInter

func (r *Redis) SInter(ctx context.Context, keys ...string) ([]string, error)

SInter returns the members of the set resulting from the intersection of all the given sets.

func (*Redis) SIsMember

func (r *Redis) SIsMember(ctx context.Context, key string, member interface{}) (bool, error)

SIsMember checks if member is a member of the set stored at key.

func (*Redis) SMembers

func (r *Redis) SMembers(ctx context.Context, key string) ([]string, error)

SMembers returns all the members of the set stored at key.

func (*Redis) SPop

func (r *Redis) SPop(ctx context.Context, key string) (string, error)

SPop removes and returns one or more random members from the set.

func (*Redis) SPopN

func (r *Redis) SPopN(ctx context.Context, key string, count int64) ([]string, error)

SPopN removes and returns count random members from the set.

func (*Redis) SRandMember

func (r *Redis) SRandMember(ctx context.Context, key string) (string, error)

SRandMember returns one or more random members from the set without removing them.

func (*Redis) SRandMemberN

func (r *Redis) SRandMemberN(ctx context.Context, key string, count int64) ([]string, error)

SRandMemberN returns count random members from the set without removing them.

func (*Redis) SRem

func (r *Redis) SRem(ctx context.Context, key string, members ...interface{}) (int64, error)

SRem removes the specified members from the set stored at key.

func (*Redis) SUnion

func (r *Redis) SUnion(ctx context.Context, keys ...string) ([]string, error)

SUnion returns the members of the set resulting from the union of all the given sets.

func (*Redis) Scan

func (r *Redis) Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanIterator

Scan iterates over keys in the database using a cursor. This is safer than Keys for large datasets as it doesn't block.

func (*Redis) Set

func (r *Redis) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set sets the value for the given key with an optional TTL. If ttl is 0, the key will not expire.

func (*Redis) SetEX

func (r *Redis) SetEX(ctx context.Context, key string, value interface{}, ttl time.Duration) error

SetEX sets the value for the given key with a TTL (shorthand for Set with TTL).

func (*Redis) SetJSON

func (r *Redis) SetJSON(ctx context.Context, key string, value interface{}, ttl time.Duration) error

SetJSON serializes the value to JSON and stores it in Redis.

func (*Redis) SetNX

func (r *Redis) SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)

SetNX sets the value for the given key only if the key does not exist. Returns true if the key was set, false if it already existed.

func (*Redis) Subscribe

func (r *Redis) Subscribe(ctx context.Context, channels ...string) *redis.PubSub

Subscribe subscribes to the given channels. Returns a PubSub instance that can be used to receive messages.

func (*Redis) TTL

func (r *Redis) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the remaining time to live of a key that has a timeout. Returns -1 if the key exists but has no associated expire. Returns -2 if the key does not exist.

func (*Redis) TxPipeline

func (r *Redis) TxPipeline() redis.Pipeliner

TxPipeline returns a new transaction pipeline. Commands in a transaction pipeline are wrapped in MULTI/EXEC.

func (*Redis) Type

func (r *Redis) Type(ctx context.Context, key string) (string, error)

Type returns the type of value stored at key.

func (*Redis) Watch

func (r *Redis) Watch(ctx context.Context, fn func(*redis.Tx) error, keys ...string) error

Watch watches the given keys for changes. If any of the watched keys are modified before EXEC, the transaction will fail.

func (*Redis) ZAdd

func (r *Redis) ZAdd(ctx context.Context, key string, members ...redis.Z) (int64, error)

ZAdd adds all the specified members with the specified scores to the sorted set stored at key.

func (*Redis) ZCard

func (r *Redis) ZCard(ctx context.Context, key string) (int64, error)

ZCard returns the number of elements in the sorted set stored at key.

func (*Redis) ZCount

func (r *Redis) ZCount(ctx context.Context, key, min, max string) (int64, error)

ZCount returns the number of elements in the sorted set with a score between min and max.

func (*Redis) ZIncrBy

func (r *Redis) ZIncrBy(ctx context.Context, key string, increment float64, member string) (float64, error)

ZIncrBy increments the score of member in the sorted set by increment.

func (*Redis) ZRange

func (r *Redis) ZRange(ctx context.Context, key string, start, stop int64) ([]string, error)

ZRange returns the specified range of elements in the sorted set stored at key. The elements are ordered from the lowest to the highest score.

func (*Redis) ZRangeByScore

func (r *Redis) ZRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)

ZRangeByScore returns all elements in the sorted set with a score between min and max.

func (*Redis) ZRangeWithScores

func (r *Redis) ZRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)

ZRangeWithScores returns the specified range with scores.

func (*Redis) ZRank

func (r *Redis) ZRank(ctx context.Context, key, member string) (int64, error)

ZRank returns the rank of member in the sorted set (0-based, lowest score first).

func (*Redis) ZRem

func (r *Redis) ZRem(ctx context.Context, key string, members ...interface{}) (int64, error)

ZRem removes the specified members from the sorted set stored at key.

func (*Redis) ZRevRange

func (r *Redis) ZRevRange(ctx context.Context, key string, start, stop int64) ([]string, error)

ZRevRange returns the specified range in reverse order (highest to lowest score).

func (*Redis) ZRevRangeByScore

func (r *Redis) ZRevRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)

ZRevRangeByScore returns all elements in the sorted set with scores between max and min (in reverse order).

func (*Redis) ZRevRangeWithScores

func (r *Redis) ZRevRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)

ZRevRangeWithScores returns the specified range in reverse order with scores.

func (*Redis) ZRevRank

func (r *Redis) ZRevRank(ctx context.Context, key, member string) (int64, error)

ZRevRank returns the rank of member in the sorted set (highest score first).

func (*Redis) ZScore

func (r *Redis) ZScore(ctx context.Context, key, member string) (float64, error)

ZScore returns the score of member in the sorted set stored at key.

type RedisLifecycleParams

type RedisLifecycleParams struct {
	fx.In

	Lifecycle fx.Lifecycle
	Client    *Redis
}

RedisLifecycleParams groups the dependencies needed for Redis lifecycle management

type RedisParams

type RedisParams struct {
	fx.In

	Config Config
	Logger Logger `optional:"true"` // Optional logger from std/v1/logger
}

RedisParams groups the dependencies needed to create a Redis client

type TLSConfig

type TLSConfig struct {
	// Enabled determines whether to use TLS/SSL for the connection
	Enabled bool

	// CACertPath is the file path to the CA certificate for verifying the server
	CACertPath string

	// ClientCertPath is the file path to the client certificate
	ClientCertPath string

	// ClientKeyPath is the file path to the client certificate's private key
	ClientKeyPath string

	// InsecureSkipVerify controls whether to skip verification of the server's certificate
	// WARNING: Setting this to true is insecure and should only be used in testing
	InsecureSkipVerify bool

	// ServerName is used to verify the hostname on the returned certificates
	// If empty, the Host from the main config is used
	ServerName string
}

TLSConfig contains TLS/SSL configuration parameters.

Jump to

Keyboard shortcuts

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