Documentation
¶
Overview ¶
Package rediscluster connects to a set of Redis nodes with health checking and load balancing across the healthy ones.
go-redis is exposed rather than wrapped: the client type it returns is go-redis's own, so every command is available without this package mirroring the API.
Index ¶
- Constants
- type ClusterAdapter
- func (ca *ClusterAdapter) Client() *redis.Client
- func (ca *ClusterAdapter) Close() error
- func (ca *ClusterAdapter) ExecuteWithRetry(ctx context.Context, fn func(context.Context, *redis.Client) error, ...) error
- func (ca *ClusterAdapter) ForceHealthCheck()
- func (ca *ClusterAdapter) GetClusterHealth() ClusterHealth
- func (ca *ClusterAdapter) GetHealthyNode() *RedisNode
- func (ca *ClusterAdapter) GetMetrics() ClusterMetrics
- func (ca *ClusterAdapter) GetNodeByIndex(index int) *RedisNode
- func (ca *ClusterAdapter) GetNodeByKey(key string) *RedisNode
- func (ca *ClusterAdapter) IsHealthy() bool
- func (ca *ClusterAdapter) MarkNodeFailed(nodeURL string)
- func (ca *ClusterAdapter) StartHealthMonitoring()
- func (ca *ClusterAdapter) WaitForHealthy(ctx context.Context, timeout time.Duration) error
- type ClusterClient
- func (c *ClusterClient) Close() error
- func (c *ClusterClient) Decr(ctx context.Context, key string) *redis.IntCmd
- func (c *ClusterClient) Del(ctx context.Context, keys ...string) *redis.IntCmd
- func (c *ClusterClient) Exists(ctx context.Context, keys ...string) *redis.IntCmd
- func (c *ClusterClient) Expire(ctx context.Context, key string, expiration time.Duration) *redis.BoolCmd
- func (c *ClusterClient) FlushDB(ctx context.Context) *redis.StatusCmd
- func (c *ClusterClient) Get(ctx context.Context, key string) *redis.StringCmd
- func (c *ClusterClient) HDel(ctx context.Context, key string, fields ...string) *redis.IntCmd
- func (c *ClusterClient) HGet(ctx context.Context, key, field string) *redis.StringCmd
- func (c *ClusterClient) HGetAll(ctx context.Context, key string) *redis.MapStringStringCmd
- func (c *ClusterClient) HSet(ctx context.Context, key string, values ...any) *redis.IntCmd
- func (c *ClusterClient) Incr(ctx context.Context, key string) *redis.IntCmd
- func (c *ClusterClient) Keys(ctx context.Context, pattern string) *redis.StringSliceCmd
- func (c *ClusterClient) LLen(ctx context.Context, key string) *redis.IntCmd
- func (c *ClusterClient) LPush(ctx context.Context, key string, values ...any) *redis.IntCmd
- func (c *ClusterClient) Ping(ctx context.Context) *redis.StatusCmd
- func (c *ClusterClient) Pipeline() redis.Pipeliner
- func (c *ClusterClient) RPop(ctx context.Context, key string) *redis.StringCmd
- func (c *ClusterClient) SAdd(ctx context.Context, key string, members ...any) *redis.IntCmd
- func (c *ClusterClient) SCard(ctx context.Context, key string) *redis.IntCmd
- func (c *ClusterClient) SMembers(ctx context.Context, key string) *redis.StringSliceCmd
- func (c *ClusterClient) SRem(ctx context.Context, key string, members ...any) *redis.IntCmd
- func (c *ClusterClient) Set(ctx context.Context, key string, value any, expiration time.Duration) *redis.StatusCmd
- func (c *ClusterClient) TTL(ctx context.Context, key string) *redis.DurationCmd
- func (c *ClusterClient) TxPipeline() redis.Pipeliner
- func (c *ClusterClient) WithContext(ctx context.Context) *ClusterClient
- type ClusterConfig
- type ClusterHealth
- type ClusterMetrics
- type NodeHealth
- type NodeState
- type RedisNode
- type TombManager
Constants ¶
const DevEnvExample = `` /* 266-byte string literal not displayed */
Single Redis (Development)
const ProdClusterExample = `` /* 589-byte string literal not displayed */
Redis Cluster (Production)
const SentinelExample = `` /* 294-byte string literal not displayed */
Sentinel Configuration
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ClusterAdapter ¶
type ClusterAdapter struct {
// contains filtered or unexported fields
}
ClusterAdapter manages connections to multiple Redis nodes
func NewClusterAdapter ¶
func NewClusterAdapter(config *ClusterConfig) (*ClusterAdapter, error)
NewClusterAdapter creates a new multi-node Redis adapter
func (*ClusterAdapter) Client ¶
func (ca *ClusterAdapter) Client() *redis.Client
Client returns a go-redis compatible client
func (*ClusterAdapter) Close ¶
func (ca *ClusterAdapter) Close() error
Close gracefully shuts down all connections. Every node is closed even if an earlier one failed; the failures are joined into the returned error rather than discarded, which is what this method used to do.
func (*ClusterAdapter) ExecuteWithRetry ¶
func (ca *ClusterAdapter) ExecuteWithRetry(ctx context.Context, fn func(context.Context, *redis.Client) error, key ...string) error
ExecuteWithRetry executes a Redis operation with retry and failover
func (*ClusterAdapter) ForceHealthCheck ¶
func (ca *ClusterAdapter) ForceHealthCheck()
ForceHealthCheck triggers an immediate health check on all nodes
func (*ClusterAdapter) GetClusterHealth ¶
func (ca *ClusterAdapter) GetClusterHealth() ClusterHealth
GetClusterHealth returns health information for all nodes
func (*ClusterAdapter) GetHealthyNode ¶
func (ca *ClusterAdapter) GetHealthyNode() *RedisNode
GetHealthyNode returns a healthy node based on load balancing strategy
func (*ClusterAdapter) GetMetrics ¶
func (ca *ClusterAdapter) GetMetrics() ClusterMetrics
GetMetrics returns cluster metrics
func (*ClusterAdapter) GetNodeByIndex ¶
func (ca *ClusterAdapter) GetNodeByIndex(index int) *RedisNode
GetNodeByIndex returns a specific node by index (for debugging)
func (*ClusterAdapter) GetNodeByKey ¶
func (ca *ClusterAdapter) GetNodeByKey(key string) *RedisNode
GetNodeByKey returns a node based on key (for hash-based routing)
func (*ClusterAdapter) IsHealthy ¶
func (ca *ClusterAdapter) IsHealthy() bool
IsHealthy returns true if at least one node is healthy
func (*ClusterAdapter) MarkNodeFailed ¶
func (ca *ClusterAdapter) MarkNodeFailed(nodeURL string)
MarkNodeFailed manually marks a node as failed
func (*ClusterAdapter) StartHealthMonitoring ¶
func (ca *ClusterAdapter) StartHealthMonitoring()
StartHealthMonitoring manually starts health monitoring (if not already started)
func (*ClusterAdapter) WaitForHealthy ¶
WaitForHealthy waits for at least one node to become healthy
type ClusterClient ¶
type ClusterClient struct {
// contains filtered or unexported fields
}
ClusterClient provides a go-redis compatible interface with cluster failover
func NewClusterClient ¶
func NewClusterClient(adapter *ClusterAdapter) *ClusterClient
NewClusterClient creates a new cluster client wrapper
func (*ClusterClient) Expire ¶
func (c *ClusterClient) Expire(ctx context.Context, key string, expiration time.Duration) *redis.BoolCmd
Expire sets a timeout on a key
func (*ClusterClient) FlushDB ¶
func (c *ClusterClient) FlushDB(ctx context.Context) *redis.StatusCmd
FlushDB removes all keys from the current database
func (*ClusterClient) HGetAll ¶
func (c *ClusterClient) HGetAll(ctx context.Context, key string) *redis.MapStringStringCmd
HGetAll returns all fields and values of the hash stored at key
func (*ClusterClient) HSet ¶
HSet sets the specified fields to their respective values in the hash stored at key
func (*ClusterClient) Keys ¶
func (c *ClusterClient) Keys(ctx context.Context, pattern string) *redis.StringSliceCmd
Keys finds all keys matching the given pattern
func (*ClusterClient) LPush ¶
LPush inserts all the specified values at the head of the list stored at key
func (*ClusterClient) Ping ¶
func (c *ClusterClient) Ping(ctx context.Context) *redis.StatusCmd
Ping pings the Redis server
func (*ClusterClient) Pipeline ¶
func (c *ClusterClient) Pipeline() redis.Pipeliner
Pipeline returns a new pipeline
func (*ClusterClient) SCard ¶
SCard returns the set cardinality (number of elements) of the set stored at key
func (*ClusterClient) SMembers ¶
func (c *ClusterClient) SMembers(ctx context.Context, key string) *redis.StringSliceCmd
SMembers returns all the members of the set value stored at key
func (*ClusterClient) Set ¶
func (c *ClusterClient) Set(ctx context.Context, key string, value any, expiration time.Duration) *redis.StatusCmd
Set sets key to hold the string value with optional expiration
func (*ClusterClient) TTL ¶
func (c *ClusterClient) TTL(ctx context.Context, key string) *redis.DurationCmd
TTL returns the remaining time to live of a key
func (*ClusterClient) TxPipeline ¶
func (c *ClusterClient) TxPipeline() redis.Pipeliner
TxPipeline returns a new transaction pipeline
func (*ClusterClient) WithContext ¶
func (c *ClusterClient) WithContext(ctx context.Context) *ClusterClient
WithContext returns a shallow copy of c with its context changed to ctx
type ClusterConfig ¶
type ClusterConfig struct {
NodeURLs []string // Redis node URLs
ServiceName string // Service identifier
Password string // Redis password (if required)
// Connection pooling
MaxPoolSize int // Maximum connections per node
MinIdleConns int // Minimum idle connections
MaxIdleTime time.Duration // Max time a connection can be idle
ConnMaxLifetime time.Duration // Max lifetime of a connection
// Health and retry settings
HealthCheckInterval time.Duration // How often to check node health
HealthCheckTimeout time.Duration // Timeout for health checks
MaxRetries int // Max retry attempts
RetryBackoffBase time.Duration // Base backoff duration
RetryBackoffMax time.Duration // Max backoff duration
// Circuit breaker
CircuitBreakerThreshold int // Failures before marking node as failed
CircuitBreakerTimeout time.Duration // Time before retrying failed node
// Load balancing
LoadBalanceStrategy string // "round_robin", "random", "hash"
}
ClusterConfig holds configuration for the Redis cluster adapter
func LoadConfigFromEnv ¶
func LoadConfigFromEnv(serviceName string) (*ClusterConfig, error)
LoadConfigFromEnv loads Redis cluster configuration from environment variables
func (*ClusterConfig) String ¶
func (c *ClusterConfig) String() string
String returns a string representation of the configuration
func (*ClusterConfig) Validate ¶
func (c *ClusterConfig) Validate() error
Validate ensures the configuration is valid
type ClusterHealth ¶
type ClusterHealth struct {
Nodes []NodeHealth
TotalNodes int
HealthyNodes int
Timestamp time.Time
}
ClusterHealth represents the health status of the cluster
type ClusterMetrics ¶
type ClusterMetrics struct {
TotalOperations int64
FailedOperations int64
AverageLatency time.Duration
MinLatency time.Duration
MaxLatency time.Duration
Timestamp time.Time
}
ClusterMetrics represents operational metrics for the cluster
type NodeHealth ¶
type NodeHealth struct {
Name string
URL string
State NodeState
LastError error
LastCheck time.Time
Latency time.Duration
OpsCount int64
ErrorCount int64
}
NodeHealth represents health information for a single node
type TombManager ¶
type TombManager struct {
// contains filtered or unexported fields
}
TombManager provides graceful background task management for Redis cluster components This follows the same patterns as the platform's database and rabbitmq cluster implementations
func NewTombManager ¶
func NewTombManager(serviceName string) *TombManager
NewTombManager creates a new background task manager for Redis operations
func (*TombManager) Context ¶
func (tm *TombManager) Context() context.Context
Context returns the cancellation context for manual task management
func (*TombManager) IsShuttingDown ¶
func (tm *TombManager) IsShuttingDown() bool
IsShuttingDown returns true if the tomb manager is shutting down
func (*TombManager) Shutdown ¶
func (tm *TombManager) Shutdown()
Shutdown gracefully stops all background tasks
func (*TombManager) StartBackgroundTask ¶
func (tm *TombManager) StartBackgroundTask(taskFn func(ctx context.Context), taskName string)
StartBackgroundTask starts a background task with proper lifecycle management
func (*TombManager) WaitGroup ¶
func (tm *TombManager) WaitGroup() *sync.WaitGroup
WaitGroup returns the wait group for manual task management