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.
Architecture ¶
This package follows the "accept interfaces, return structs" design pattern:
- Client interface: Defines the contract for Redis operations
- RedisClient struct: Concrete implementation of the Client interface
- NewClient constructor: Returns *RedisClient (concrete type)
- FX module: Provides both *RedisClient and Client interface for dependency injection
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
Direct Usage (Without FX) ¶
For simple applications or tests, create a client directly:
import (
"github.com/Aleph-Alpha/std/v1/redis"
"context"
"time"
)
// Create a new Redis client (returns concrete *RedisClient)
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()
// Use the client
ctx := context.Background()
err = client.Set(ctx, "user:123", "John Doe", 5*time.Minute)
FX Module Integration ¶
For production applications using Uber's fx, use the FXModule which provides both the concrete type and interface:
import (
"github.com/Aleph-Alpha/std/v1/redis"
"github.com/Aleph-Alpha/std/v1/logger"
"go.uber.org/fx"
)
app := fx.New(
logger.FXModule, // Optional: provides std logger
redis.FXModule, // Provides *RedisClient and redis.Client interface
fx.Provide(func() redis.Config {
return redis.Config{
Host: "localhost",
Port: 6379,
}
}),
fx.Invoke(func(client *redis.RedisClient) {
// Use concrete type directly
ctx := context.Background()
client.Set(ctx, "key", "value", 0)
}),
// ... other modules
)
app.Run()
Observability (Observer Hook) ¶
Redis supports optional observability through the Observer interface from the observability package. This allows external systems to track Redis operations without coupling the package to specific metrics/tracing implementations.
Using WithObserver (non-FX usage):
client, err := redis.NewClient(config)
if err != nil {
return err
}
client = client.WithObserver(myObserver).WithLogger(myLogger)
defer client.Close()
Using FX (automatic injection):
app := fx.New(
redis.FXModule,
logger.FXModule, // Optional: provides logger
fx.Provide(
func() redis.Config { return loadConfig() },
func() observability.Observer { return myObserver }, // Optional
),
)
The observer receives events for Redis operations:
- Component: "redis"
- Operations: "get", "set", "setnx", "delete", "mget", "mset", "hget", "hset", "hgetall", "lpush", "lrange", "publish"
- Resource: key name (or first key for multi-key operations)
- SubResource: field name (for hash operations) or channel name
- Duration: operation duration
- Error: any error that occurred
- Size: bytes or count returned/affected
- Metadata: operation-specific details (e.g., ttl, key_count, field_count)
Type Aliases in Consumer Code ¶
To simplify your code and make it database-agnostic, use type aliases:
package myapp
import stdRedis "github.com/Aleph-Alpha/std/v1/redis"
// Use type alias to reference std's interface
type RedisClient = stdRedis.Client
// Now use RedisClient throughout your codebase
func MyFunction(client RedisClient) {
client.Get(ctx, "key")
}
This eliminates the need for adapters and allows you to switch implementations by only changing the alias definition.
Basic 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 ¶
// 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
// ...
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
- Variables
- func IsClosedError(err error) bool
- func IsNilError(err error) bool
- func IsPoolTimeoutError(err error) bool
- func RegisterRedisLifecycle(params RedisLifecycleParams)
- type Client
- type ClusterConfig
- type ClusterRedisParams
- type Config
- type FailoverConfig
- type FailoverRedisParams
- type Lock
- type Logger
- type RedisClient
- func NewClient(cfg Config) (*RedisClient, error)
- func NewClientWithDI(params RedisParams) (*RedisClient, error)
- func NewClusterClient(cfg ClusterConfig) (*RedisClient, error)
- func NewClusterClientWithDI(params ClusterRedisParams) (*RedisClient, error)
- func NewFailoverClient(cfg FailoverConfig) (*RedisClient, error)
- func NewFailoverClientWithDI(params FailoverRedisParams) (*RedisClient, error)
- func (r *RedisClient) AcquireLock(ctx context.Context, key string, ttl time.Duration) (*Lock, error)
- func (r *RedisClient) BLPop(ctx context.Context, timeout time.Duration, keys ...string) ([]string, error)
- func (r *RedisClient) BRPop(ctx context.Context, timeout time.Duration, keys ...string) ([]string, error)
- func (r *RedisClient) Client() redis.UniversalClient
- func (r *RedisClient) Close() error
- func (r *RedisClient) Decr(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) DecrBy(ctx context.Context, key string, value int64) (int64, error)
- func (r *RedisClient) Delete(ctx context.Context, keys ...string) (int64, error)
- func (r *RedisClient) Exists(ctx context.Context, keys ...string) (int64, error)
- func (r *RedisClient) Expire(ctx context.Context, key string, ttl time.Duration) (bool, error)
- func (r *RedisClient) ExpireAt(ctx context.Context, key string, tm time.Time) (bool, error)
- func (r *RedisClient) Get(ctx context.Context, key string) (string, error)
- func (r *RedisClient) GetJSON(ctx context.Context, key string, dest interface{}) error
- func (r *RedisClient) GetSet(ctx context.Context, key string, value interface{}) (string, error)
- func (r *RedisClient) HDel(ctx context.Context, key string, fields ...string) (int64, error)
- func (r *RedisClient) HExists(ctx context.Context, key, field string) (bool, error)
- func (r *RedisClient) HGet(ctx context.Context, key, field string) (string, error)
- func (r *RedisClient) HGetAll(ctx context.Context, key string) (map[string]string, error)
- func (r *RedisClient) HIncrBy(ctx context.Context, key, field string, incr int64) (int64, error)
- func (r *RedisClient) HIncrByFloat(ctx context.Context, key, field string, incr float64) (float64, error)
- func (r *RedisClient) HKeys(ctx context.Context, key string) ([]string, error)
- func (r *RedisClient) HLen(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) HMGet(ctx context.Context, key string, fields ...string) ([]interface{}, error)
- func (r *RedisClient) HSet(ctx context.Context, key string, values ...interface{}) (int64, error)
- func (r *RedisClient) HVals(ctx context.Context, key string) ([]string, error)
- func (r *RedisClient) Incr(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) IncrBy(ctx context.Context, key string, value int64) (int64, error)
- func (r *RedisClient) IncrByFloat(ctx context.Context, key string, value float64) (float64, error)
- func (r *RedisClient) Keys(ctx context.Context, pattern string) ([]string, error)
- func (r *RedisClient) LIndex(ctx context.Context, key string, index int64) (string, error)
- func (r *RedisClient) LLen(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) LPop(ctx context.Context, key string) (string, error)
- func (r *RedisClient) LPush(ctx context.Context, key string, values ...interface{}) (int64, error)
- func (r *RedisClient) LRange(ctx context.Context, key string, start, stop int64) ([]string, error)
- func (r *RedisClient) LRem(ctx context.Context, key string, count int64, value interface{}) (int64, error)
- func (r *RedisClient) LSet(ctx context.Context, key string, index int64, value interface{}) error
- func (r *RedisClient) LTrim(ctx context.Context, key string, start, stop int64) error
- func (r *RedisClient) MGet(ctx context.Context, keys ...string) ([]interface{}, error)
- func (r *RedisClient) MSet(ctx context.Context, values ...interface{}) error
- func (r *RedisClient) PSubscribe(ctx context.Context, patterns ...string) *redis.PubSub
- func (r *RedisClient) Persist(ctx context.Context, key string) (bool, error)
- func (r *RedisClient) Ping(ctx context.Context) error
- func (r *RedisClient) Pipeline() redis.Pipeliner
- func (r *RedisClient) PoolStats() *redis.PoolStats
- func (r *RedisClient) Publish(ctx context.Context, channel string, message interface{}) (int64, error)
- func (r *RedisClient) RPop(ctx context.Context, key string) (string, error)
- func (r *RedisClient) RPush(ctx context.Context, key string, values ...interface{}) (int64, error)
- func (r *RedisClient) RateLimit(ctx context.Context, key string, limit int64, window time.Duration) (bool, error)
- func (r *RedisClient) SAdd(ctx context.Context, key string, members ...interface{}) (int64, error)
- func (r *RedisClient) SCard(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) SDiff(ctx context.Context, keys ...string) ([]string, error)
- func (r *RedisClient) SInter(ctx context.Context, keys ...string) ([]string, error)
- func (r *RedisClient) SIsMember(ctx context.Context, key string, member interface{}) (bool, error)
- func (r *RedisClient) SMembers(ctx context.Context, key string) ([]string, error)
- func (r *RedisClient) SPop(ctx context.Context, key string) (string, error)
- func (r *RedisClient) SPopN(ctx context.Context, key string, count int64) ([]string, error)
- func (r *RedisClient) SRandMember(ctx context.Context, key string) (string, error)
- func (r *RedisClient) SRandMemberN(ctx context.Context, key string, count int64) ([]string, error)
- func (r *RedisClient) SRem(ctx context.Context, key string, members ...interface{}) (int64, error)
- func (r *RedisClient) SUnion(ctx context.Context, keys ...string) ([]string, error)
- func (r *RedisClient) Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanIterator
- func (r *RedisClient) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (r *RedisClient) SetEX(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (r *RedisClient) SetJSON(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (r *RedisClient) SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)
- func (r *RedisClient) Subscribe(ctx context.Context, channels ...string) *redis.PubSub
- func (r *RedisClient) TTL(ctx context.Context, key string) (time.Duration, error)
- func (r *RedisClient) TxPipeline() redis.Pipeliner
- func (r *RedisClient) Type(ctx context.Context, key string) (string, error)
- func (r *RedisClient) Watch(ctx context.Context, fn func(*redis.Tx) error, keys ...string) error
- func (r *RedisClient) WithLogger(logger Logger) *RedisClient
- func (r *RedisClient) WithObserver(observer observability.Observer) *RedisClient
- func (r *RedisClient) ZAdd(ctx context.Context, key string, members ...redis.Z) (int64, error)
- func (r *RedisClient) ZCard(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) ZCount(ctx context.Context, key, min, max string) (int64, error)
- func (r *RedisClient) ZIncrBy(ctx context.Context, key string, increment float64, member string) (float64, error)
- func (r *RedisClient) ZRange(ctx context.Context, key string, start, stop int64) ([]string, error)
- func (r *RedisClient) ZRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)
- func (r *RedisClient) ZRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)
- func (r *RedisClient) ZRank(ctx context.Context, key, member string) (int64, error)
- func (r *RedisClient) ZRem(ctx context.Context, key string, members ...interface{}) (int64, error)
- func (r *RedisClient) ZRevRange(ctx context.Context, key string, start, stop int64) ([]string, error)
- func (r *RedisClient) ZRevRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)
- func (r *RedisClient) ZRevRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)
- func (r *RedisClient) ZRevRank(ctx context.Context, key, member string) (int64, error)
- func (r *RedisClient) ZScore(ctx context.Context, key, member string) (float64, error)
- type RedisLifecycleParams
- type RedisParams
- type TLSConfig
Constants ¶
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 ¶
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
var ClusterFXModule = fx.Module("redis-cluster", fx.Provide( NewClusterClientWithDI, ), fx.Invoke(RegisterRedisLifecycle), )
ClusterFXModule is an fx.Module for Redis Cluster configuration.
var FXModule = fx.Module("redis", fx.Provide( NewClientWithDI, ), fx.Invoke(RegisterRedisLifecycle), )
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...
)
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 ¶
IsClosedError checks if the error is a "client is closed" error.
func IsNilError ¶
IsNilError checks if the error is a "key does not exist" error.
func IsPoolTimeoutError ¶
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:
- On application start: Pings Redis to ensure the connection is healthy
- 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 Client ¶ added in v0.12.0
type Client interface {
// Connection and lifecycle
Ping(ctx context.Context) error
PoolStats() *redis.PoolStats
Client() redis.UniversalClient
Close() error
// String operations
Get(ctx context.Context, key string) (string, error)
Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)
SetEX(ctx context.Context, key string, value interface{}, ttl time.Duration) error
GetSet(ctx context.Context, key string, value interface{}) (string, error)
MGet(ctx context.Context, keys ...string) ([]interface{}, error)
MSet(ctx context.Context, values ...interface{}) error
// Key operations
Delete(ctx context.Context, keys ...string) (int64, error)
Exists(ctx context.Context, keys ...string) (int64, error)
Expire(ctx context.Context, key string, ttl time.Duration) (bool, error)
ExpireAt(ctx context.Context, key string, tm time.Time) (bool, error)
TTL(ctx context.Context, key string) (time.Duration, error)
Persist(ctx context.Context, key string) (bool, error)
Keys(ctx context.Context, pattern string) ([]string, error)
Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanIterator
Type(ctx context.Context, key string) (string, error)
// Numeric operations
Incr(ctx context.Context, key string) (int64, error)
IncrBy(ctx context.Context, key string, value int64) (int64, error)
IncrByFloat(ctx context.Context, key string, value float64) (float64, error)
Decr(ctx context.Context, key string) (int64, error)
DecrBy(ctx context.Context, key string, value int64) (int64, error)
// Hash operations
HSet(ctx context.Context, key string, values ...interface{}) (int64, error)
HGet(ctx context.Context, key, field string) (string, error)
HGetAll(ctx context.Context, key string) (map[string]string, error)
HMGet(ctx context.Context, key string, fields ...string) ([]interface{}, error)
HExists(ctx context.Context, key, field string) (bool, error)
HDel(ctx context.Context, key string, fields ...string) (int64, error)
HLen(ctx context.Context, key string) (int64, error)
HKeys(ctx context.Context, key string) ([]string, error)
HVals(ctx context.Context, key string) ([]string, error)
HIncrBy(ctx context.Context, key, field string, incr int64) (int64, error)
HIncrByFloat(ctx context.Context, key, field string, incr float64) (float64, error)
// List operations
LPush(ctx context.Context, key string, values ...interface{}) (int64, error)
RPush(ctx context.Context, key string, values ...interface{}) (int64, error)
LPop(ctx context.Context, key string) (string, error)
RPop(ctx context.Context, key string) (string, error)
LRange(ctx context.Context, key string, start, stop int64) ([]string, error)
LLen(ctx context.Context, key string) (int64, error)
LRem(ctx context.Context, key string, count int64, value interface{}) (int64, error)
LTrim(ctx context.Context, key string, start, stop int64) error
LIndex(ctx context.Context, key string, index int64) (string, error)
LSet(ctx context.Context, key string, index int64, value interface{}) error
BLPop(ctx context.Context, timeout time.Duration, keys ...string) ([]string, error)
BRPop(ctx context.Context, timeout time.Duration, keys ...string) ([]string, error)
// Set operations
SAdd(ctx context.Context, key string, members ...interface{}) (int64, error)
SRem(ctx context.Context, key string, members ...interface{}) (int64, error)
SMembers(ctx context.Context, key string) ([]string, error)
SIsMember(ctx context.Context, key string, member interface{}) (bool, error)
SCard(ctx context.Context, key string) (int64, error)
SPop(ctx context.Context, key string) (string, error)
SPopN(ctx context.Context, key string, count int64) ([]string, error)
SRandMember(ctx context.Context, key string) (string, error)
SRandMemberN(ctx context.Context, key string, count int64) ([]string, error)
SInter(ctx context.Context, keys ...string) ([]string, error)
SUnion(ctx context.Context, keys ...string) ([]string, error)
SDiff(ctx context.Context, keys ...string) ([]string, error)
// Sorted set operations
ZAdd(ctx context.Context, key string, members ...redis.Z) (int64, error)
ZRem(ctx context.Context, key string, members ...interface{}) (int64, error)
ZRange(ctx context.Context, key string, start, stop int64) ([]string, error)
ZRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)
ZRevRange(ctx context.Context, key string, start, stop int64) ([]string, error)
ZRevRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)
ZRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)
ZRevRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)
ZScore(ctx context.Context, key, member string) (float64, error)
ZCard(ctx context.Context, key string) (int64, error)
ZCount(ctx context.Context, key, min, max string) (int64, error)
ZIncrBy(ctx context.Context, key string, increment float64, member string) (float64, error)
ZRank(ctx context.Context, key, member string) (int64, error)
ZRevRank(ctx context.Context, key, member string) (int64, error)
// Pub/Sub operations
Publish(ctx context.Context, channel string, message interface{}) (int64, error)
Subscribe(ctx context.Context, channels ...string) *redis.PubSub
PSubscribe(ctx context.Context, patterns ...string) *redis.PubSub
// Transaction and pipeline operations
Pipeline() redis.Pipeliner
TxPipeline() redis.Pipeliner
Watch(ctx context.Context, fn func(*redis.Tx) error, keys ...string) error
// Advanced operations
SetJSON(ctx context.Context, key string, value interface{}, ttl time.Duration) error
GetJSON(ctx context.Context, key string, dest interface{}) error
AcquireLock(ctx context.Context, key string, ttl time.Duration) (*Lock, error)
RateLimit(ctx context.Context, key string, limit int64, window time.Duration) (bool, error)
}
Client provides a high-level interface for interacting with Redis. It abstracts Redis operations with support for strings, hashes, lists, sets, sorted sets, pub/sub, transactions, and advanced features like distributed locks and rate limiting.
This interface is implemented by the concrete *RedisClient type.
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"`
Observer observability.Observer `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"`
Observer observability.Observer `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.
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 RedisClient ¶ added in v0.12.0
type RedisClient struct {
// contains filtered or unexported fields
}
RedisClient represents a client for interacting with Redis. It wraps the go-redis client and provides a simplified interface with connection management and helper methods.
RedisClient implements the Client interface.
func NewClient ¶
func NewClient(cfg Config) (*RedisClient, 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) (*RedisClient, 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) (*RedisClient, 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) (*RedisClient, error)
NewClusterClientWithDI creates a new Redis Cluster client using dependency injection.
func NewFailoverClient ¶
func NewFailoverClient(cfg FailoverConfig) (*RedisClient, 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) (*RedisClient, error)
NewFailoverClientWithDI creates a new Redis Sentinel client using dependency injection.
func (*RedisClient) AcquireLock ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) BLPop ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) BRPop ¶ added in v0.12.0
func (r *RedisClient) BRPop(ctx context.Context, timeout time.Duration, keys ...string) ([]string, error)
BRPop is a blocking version of RPop with a timeout.
func (*RedisClient) Client ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) Close ¶ added in v0.12.0
func (r *RedisClient) Close() error
Close closes the Redis client and releases all resources. This should be called when the client is no longer needed.
func (*RedisClient) DecrBy ¶ added in v0.12.0
DecrBy decrements the integer value of a key by the given amount.
func (*RedisClient) Delete ¶ added in v0.12.0
Delete deletes one or more keys. Returns the number of keys that were deleted.
func (*RedisClient) Exists ¶ added in v0.12.0
Exists checks if one or more keys exist. Returns the number of keys that exist.
func (*RedisClient) Expire ¶ added in v0.12.0
Expire sets a timeout on a key. After the timeout has expired, the key will be automatically deleted.
func (*RedisClient) ExpireAt ¶ added in v0.12.0
ExpireAt sets an expiration timestamp on a key. The key will be deleted when the timestamp is reached.
func (*RedisClient) Get ¶ added in v0.12.0
Get retrieves the value associated with the given key. Returns ErrNil if the key does not exist.
func (*RedisClient) GetJSON ¶ added in v0.12.0
func (r *RedisClient) GetJSON(ctx context.Context, key string, dest interface{}) error
GetJSON retrieves the value from Redis and deserializes it from JSON.
func (*RedisClient) GetSet ¶ added in v0.12.0
GetSet sets the value for the given key and returns the old value.
func (*RedisClient) HExists ¶ added in v0.12.0
HExists checks if a field exists in the hash stored at key.
func (*RedisClient) HGet ¶ added in v0.12.0
HGet returns the value associated with field in the hash stored at key.
func (*RedisClient) HGetAll ¶ added in v0.12.0
HGetAll returns all fields and values in the hash stored at key.
func (*RedisClient) HIncrBy ¶ added in v0.12.0
HIncrBy increments the integer value of a hash field by the given number.
func (*RedisClient) HIncrByFloat ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) HKeys ¶ added in v0.12.0
HKeys returns all field names in the hash stored at key.
func (*RedisClient) HLen ¶ added in v0.12.0
HLen returns the number of fields in the hash stored at key.
func (*RedisClient) HMGet ¶ added in v0.12.0
func (r *RedisClient) HMGet(ctx context.Context, key string, fields ...string) ([]interface{}, error)
HMGet returns the values associated with the specified fields in the hash.
func (*RedisClient) HSet ¶ added in v0.12.0
HSet sets field in the hash stored at key to value. If the key doesn't exist, a new hash is created.
func (*RedisClient) Incr ¶ added in v0.12.0
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 (*RedisClient) IncrBy ¶ added in v0.12.0
IncrBy increments the integer value of a key by the given amount.
func (*RedisClient) IncrByFloat ¶ added in v0.12.0
IncrByFloat increments the float value of a key by the given amount.
func (*RedisClient) Keys ¶ added in v0.12.0
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 (*RedisClient) LIndex ¶ added in v0.12.0
LIndex returns the element at index in the list stored at key.
func (*RedisClient) LPop ¶ added in v0.12.0
LPop removes and returns the first element of the list stored at key.
func (*RedisClient) LPush ¶ added in v0.12.0
LPush inserts all the specified values at the head of the list stored at key.
func (*RedisClient) LRange ¶ added in v0.12.0
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 (*RedisClient) LRem ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) MGet ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) MSet ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) PSubscribe ¶ added in v0.12.0
PSubscribe subscribes to channels matching the given patterns.
func (*RedisClient) Ping ¶ added in v0.12.0
func (r *RedisClient) Ping(ctx context.Context) error
Ping checks if the Redis server is reachable and responsive. It returns an error if the connection fails.
func (*RedisClient) Pipeline ¶ added in v0.12.0
func (r *RedisClient) Pipeline() redis.Pipeliner
Pipeline returns a new pipeline. Pipelines allow sending multiple commands in a single request.
func (*RedisClient) PoolStats ¶ added in v0.12.0
func (r *RedisClient) PoolStats() *redis.PoolStats
PoolStats returns connection pool statistics. Useful for monitoring connection pool health.
func (*RedisClient) Publish ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) RPop ¶ added in v0.12.0
RPop removes and returns the last element of the list stored at key.
func (*RedisClient) RPush ¶ added in v0.12.0
RPush inserts all the specified values at the tail of the list stored at key.
func (*RedisClient) RateLimit ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) SAdd ¶ added in v0.12.0
SAdd adds the specified members to the set stored at key.
func (*RedisClient) SCard ¶ added in v0.12.0
SCard returns the number of elements in the set stored at key.
func (*RedisClient) SDiff ¶ added in v0.12.0
SDiff returns the members of the set resulting from the difference between the first set and all the successive sets.
func (*RedisClient) SInter ¶ added in v0.12.0
SInter returns the members of the set resulting from the intersection of all the given sets.
func (*RedisClient) SIsMember ¶ added in v0.12.0
SIsMember checks if member is a member of the set stored at key.
func (*RedisClient) SMembers ¶ added in v0.12.0
SMembers returns all the members of the set stored at key.
func (*RedisClient) SPop ¶ added in v0.12.0
SPop removes and returns one or more random members from the set.
func (*RedisClient) SPopN ¶ added in v0.12.0
SPopN removes and returns count random members from the set.
func (*RedisClient) SRandMember ¶ added in v0.12.0
SRandMember returns one or more random members from the set without removing them.
func (*RedisClient) SRandMemberN ¶ added in v0.12.0
SRandMemberN returns count random members from the set without removing them.
func (*RedisClient) SRem ¶ added in v0.12.0
SRem removes the specified members from the set stored at key.
func (*RedisClient) SUnion ¶ added in v0.12.0
SUnion returns the members of the set resulting from the union of all the given sets.
func (*RedisClient) Scan ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) Set ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) SetEX ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) SetJSON ¶ added in v0.12.0
func (r *RedisClient) SetJSON(ctx context.Context, key string, value interface{}, ttl time.Duration) error
SetJSON serializes the value to JSON and stores it in Redis.
func (*RedisClient) SetNX ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) Subscribe ¶ added in v0.12.0
Subscribe subscribes to the given channels. Returns a PubSub instance that can be used to receive messages.
func (*RedisClient) TTL ¶ added in v0.12.0
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 (*RedisClient) TxPipeline ¶ added in v0.12.0
func (r *RedisClient) TxPipeline() redis.Pipeliner
TxPipeline returns a new transaction pipeline. Commands in a transaction pipeline are wrapped in MULTI/EXEC.
func (*RedisClient) Watch ¶ added in v0.12.0
Watch watches the given keys for changes. If any of the watched keys are modified before EXEC, the transaction will fail.
func (*RedisClient) WithLogger ¶ added in v0.13.0
func (r *RedisClient) WithLogger(logger Logger) *RedisClient
WithLogger sets the logger for this client and returns the client for method chaining. The logger is used for structured logging of client operations and errors.
Example:
client := client.WithObserver(myObserver).WithLogger(myLogger)
func (*RedisClient) WithObserver ¶ added in v0.13.0
func (r *RedisClient) WithObserver(observer observability.Observer) *RedisClient
WithObserver sets the observer for this client and returns the client for method chaining. The observer receives events about Redis operations (e.g., get, set, delete).
Example:
client := client.WithObserver(myObserver).WithLogger(myLogger)
func (*RedisClient) ZAdd ¶ added in v0.12.0
ZAdd adds all the specified members with the specified scores to the sorted set stored at key.
func (*RedisClient) ZCard ¶ added in v0.12.0
ZCard returns the number of elements in the sorted set stored at key.
func (*RedisClient) ZCount ¶ added in v0.12.0
ZCount returns the number of elements in the sorted set with a score between min and max.
func (*RedisClient) ZIncrBy ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) ZRange ¶ added in v0.12.0
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 (*RedisClient) ZRangeByScore ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) ZRangeWithScores ¶ added in v0.12.0
func (r *RedisClient) ZRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)
ZRangeWithScores returns the specified range with scores.
func (*RedisClient) ZRank ¶ added in v0.12.0
ZRank returns the rank of member in the sorted set (0-based, lowest score first).
func (*RedisClient) ZRem ¶ added in v0.12.0
ZRem removes the specified members from the sorted set stored at key.
func (*RedisClient) ZRevRange ¶ added in v0.12.0
func (r *RedisClient) ZRevRange(ctx context.Context, key string, start, stop int64) ([]string, error)
ZRevRange returns the specified range in reverse order (highest to lowest score).
func (*RedisClient) ZRevRangeByScore ¶ added in v0.12.0
func (r *RedisClient) 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 (*RedisClient) ZRevRangeWithScores ¶ added in v0.12.0
func (r *RedisClient) ZRevRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)
ZRevRangeWithScores returns the specified range in reverse order with scores.
type RedisLifecycleParams ¶
type RedisLifecycleParams struct {
fx.In
Lifecycle fx.Lifecycle
Client *RedisClient
}
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
Observer observability.Observer `optional:"true"` // Optional observer from std/v1/observability
}
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.