rediscluster

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

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

View Source
const DevEnvExample = `` /* 266-byte string literal not displayed */

Single Redis (Development)

View Source
const ProdClusterExample = `` /* 589-byte string literal not displayed */

Redis Cluster (Production)

View Source
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

func (ca *ClusterAdapter) WaitForHealthy(ctx context.Context, timeout time.Duration) error

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) Close

func (c *ClusterClient) Close() error

Close closes the cluster client

func (*ClusterClient) Decr

func (c *ClusterClient) Decr(ctx context.Context, key string) *redis.IntCmd

Decr decrements the number stored at key by one

func (*ClusterClient) Del

func (c *ClusterClient) Del(ctx context.Context, keys ...string) *redis.IntCmd

Del deletes the specified keys

func (*ClusterClient) Exists

func (c *ClusterClient) Exists(ctx context.Context, keys ...string) *redis.IntCmd

Exists checks if keys exist

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) Get

func (c *ClusterClient) Get(ctx context.Context, key string) *redis.StringCmd

Get returns the value of key

func (*ClusterClient) HDel

func (c *ClusterClient) HDel(ctx context.Context, key string, fields ...string) *redis.IntCmd

HDel deletes one or more hash fields

func (*ClusterClient) HGet

func (c *ClusterClient) HGet(ctx context.Context, key, field string) *redis.StringCmd

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

func (*ClusterClient) HGetAll

HGetAll returns all fields and values of the hash stored at key

func (*ClusterClient) HSet

func (c *ClusterClient) HSet(ctx context.Context, key string, values ...any) *redis.IntCmd

HSet sets the specified fields to their respective values in the hash stored at key

func (*ClusterClient) Incr

func (c *ClusterClient) Incr(ctx context.Context, key string) *redis.IntCmd

Incr increments the number stored at key by one

func (*ClusterClient) Keys

func (c *ClusterClient) Keys(ctx context.Context, pattern string) *redis.StringSliceCmd

Keys finds all keys matching the given pattern

func (*ClusterClient) LLen

func (c *ClusterClient) LLen(ctx context.Context, key string) *redis.IntCmd

LLen returns the length of the list stored at key

func (*ClusterClient) LPush

func (c *ClusterClient) LPush(ctx context.Context, key string, values ...any) *redis.IntCmd

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

func (*ClusterClient) Ping

Ping pings the Redis server

func (*ClusterClient) Pipeline

func (c *ClusterClient) Pipeline() redis.Pipeliner

Pipeline returns a new pipeline

func (*ClusterClient) RPop

func (c *ClusterClient) RPop(ctx context.Context, key string) *redis.StringCmd

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

func (*ClusterClient) SAdd

func (c *ClusterClient) SAdd(ctx context.Context, key string, members ...any) *redis.IntCmd

SAdd adds the specified members to the set stored at key

func (*ClusterClient) SCard

func (c *ClusterClient) SCard(ctx context.Context, key string) *redis.IntCmd

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) SRem

func (c *ClusterClient) SRem(ctx context.Context, key string, members ...any) *redis.IntCmd

SRem removes the specified members from the set 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

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 NodeState

type NodeState int

NodeState represents the health state of a Redis node

const (
	NodeHealthy NodeState = iota
	NodeDegraded
	NodeFailed
)

func (NodeState) String

func (s NodeState) String() string

type RedisNode

type RedisNode struct {
	URL  string
	Name string
	// contains filtered or unexported fields
}

RedisNode represents a single Redis instance

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

Jump to

Keyboard shortcuts

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