Documentation
¶
Overview ¶
distlock.go
Package cydist provides a generic in-memory event store backed by Redis.
Index ¶
- func CacheWrap[T any](w *CacheWrapper, fn func(context.Context) (T, error), opts ...CacheFuncOption) func(context.Context) (T, error)
- func CacheWrap1[T, A any](w *CacheWrapper, fn func(context.Context, A) (T, error), ...) func(context.Context, A) (T, error)
- func CacheWrap2[T, A, B any](w *CacheWrapper, fn func(context.Context, A, B) (T, error), ...) func(context.Context, A, B) (T, error)
- func CacheWrap3[T, A, B, C any](w *CacheWrapper, fn func(context.Context, A, B, C) (T, error), ...) func(context.Context, A, B, C) (T, error)
- func CacheWrap4[T, A, B, C, D any](w *CacheWrapper, fn func(context.Context, A, B, C, D) (T, error), ...) func(context.Context, A, B, C, D) (T, error)
- func InitDefault(opts ...Option)
- func UnmarshalPayloadTyped[T any](payload []byte) (T, error)
- type BloomFilter
- type Broadcaster
- func (b *Broadcaster) PublishSimple(channel string, payload interface{}) error
- func (b *Broadcaster) RegisterHandler(messageType string, handler TaskHandler) error
- func (b *Broadcaster) RegisterHandlerFunc(messageType string, ...) error
- func (b *Broadcaster) Shutdown()
- func (b *Broadcaster) Start(ctx context.Context) error
- type BroadcasterConfig
- type BroadcasterOption
- type CacheFuncOption
- func WithDisabled(disabled bool) CacheFuncOption
- func WithKey(key string) CacheFuncOption
- func WithKeyGenerator(gen func(ctx context.Context, args ...interface{}) string) CacheFuncOption
- func WithKeyPrefix(prefix string) CacheFuncOption
- func WithRedisClient(client *RedisClient) CacheFuncOption
- func WithTTL(ttl time.Duration) CacheFuncOption
- type CacheFuncOptions
- type CacheStats
- type CacheWrapper
- func (w *CacheWrapper) Close()
- func (w *CacheWrapper) Delete(ctx context.Context, key string) error
- func (w *CacheWrapper) Get(ctx context.Context, key string, value any) error
- func (w *CacheWrapper) GetStats() CacheStats
- func (w *CacheWrapper) ResetCacheByBaseKey(ctx context.Context, baseKey string) error
- func (w *CacheWrapper) ResetCacheByKey(ctx context.Context, key string) error
- func (w *CacheWrapper) Set(ctx context.Context, key string, value any, opts ...CacheFuncOption) error
- func (w *CacheWrapper) WrapFunc(fn interface{}, opts ...CacheFuncOption) interface{}
- type Config
- type Counter
- func (c *Counter) Decrement(ctx context.Context, amount int64) (int64, error)
- func (c *Counter) Get(ctx context.Context) (int64, error)
- func (c *Counter) Increment(ctx context.Context, amount int64) (int64, error)
- func (c *Counter) Reset(ctx context.Context) error
- func (c *Counter) SetExpiry(ctx context.Context, expiry time.Duration) (bool, error)
- type DLockOption
- type DistLock
- type DistLockManager
- type DistributedScheduler
- func (s *DistributedScheduler) AddTask(task *Task) (cron.EntryID, error)
- func (s *DistributedScheduler) ListTasks() map[string]string
- func (s *DistributedScheduler) RemoveTask(taskID string) bool
- func (s *DistributedScheduler) Start()
- func (s *DistributedScheduler) Stop()
- func (s *DistributedScheduler) StopRunningTask(taskID string) bool
- type HandlerFunc
- type KeyConfig
- type KeyNotConfiguredError
- type LocalConsumer
- type LocalMessage
- type LocalPublisher
- type LockOption
- type Mode
- type Option
- func WithAddr(addr string) Option
- func WithAddrs(addrs []string) Option
- func WithDB(db int) Option
- func WithDialTimeout(dialTimeout time.Duration) Option
- func WithIdleTimeout(idleTimeout time.Duration) Option
- func WithMasterName(masterName string) Option
- func WithMaxRedirects(maxRedirects int) Option
- func WithMaxRetries(maxRetries int) Option
- func WithMaxRetryBackoff(maxRetryBackoff time.Duration) Option
- func WithMinIdleConns(minIdleConns int) Option
- func WithMinRetryBackoff(minRetryBackoff time.Duration) Option
- func WithMode(mode Mode) Option
- func WithPassword(password string) Option
- func WithPoolSize(poolSize int) Option
- func WithPoolTimeout(poolTimeout time.Duration) Option
- func WithReadTimeout(readTimeout time.Duration) Option
- func WithRouteByLatency(routeByLatency bool) Option
- func WithRouteRandomly(routeRandomly bool) Option
- func WithSentinelAddrs(sentinelAddrs []string) Option
- func WithSentinelPassword(sentinelPassword string) Option
- func WithWriteTimeout(writeTimeout time.Duration) Option
- type PubSub
- type RateLimiter
- type Record
- type RecordStore
- func (ms *RecordStore[T]) CreateKey(ctx context.Context, key string, expire time.Duration, maxRecords int64) error
- func (ms *RecordStore[T]) DeleteKey(ctx context.Context, key string) (int64, int64, error)
- func (ms *RecordStore[T]) GetLatestRecords(ctx context.Context, key string, count int64) ([]Record[T], error)
- func (ms *RecordStore[T]) GetRecordCount(ctx context.Context, key string) (int64, error)
- func (ms *RecordStore[T]) IsKeyCreated(ctx context.Context, key string) (bool, error)
- func (ms *RecordStore[T]) SetConfigCacheTTL(ttl time.Duration)
- func (ms *RecordStore[T]) WriteRecord(ctx context.Context, key string, data T) error
- type RedisClient
- func (c *RedisClient) Client() *redis.Client
- func (c *RedisClient) Close() error
- func (c *RedisClient) Decr(ctx context.Context, key string) (int64, error)
- func (c *RedisClient) DecrBy(ctx context.Context, key string, value int64) (int64, error)
- func (c *RedisClient) Del(ctx context.Context, key string) (int64, error)
- func (c *RedisClient) Eval(ctx context.Context, script string, keys []string, args ...interface{}) (interface{}, error)
- func (c *RedisClient) Exists(ctx context.Context, keys ...string) (int64, error)
- func (c *RedisClient) Expire(ctx context.Context, key string, expiration time.Duration) (bool, error)
- func (c *RedisClient) Get(ctx context.Context, key string) (string, error)
- func (c *RedisClient) GetBytes(ctx context.Context, key string) ([]byte, error)
- func (c *RedisClient) GetObject(ctx context.Context, key string, value interface{}) error
- func (c *RedisClient) HDel(ctx context.Context, key string, fields ...string) (int64, error)
- func (c *RedisClient) HExists(ctx context.Context, key, field string) (bool, error)
- func (c *RedisClient) HGet(ctx context.Context, key, field string) (string, error)
- func (c *RedisClient) HGetAll(ctx context.Context, key string) (map[string]string, error)
- func (c *RedisClient) HKeys(ctx context.Context, key string) ([]string, error)
- func (c *RedisClient) HLen(ctx context.Context, key string) (int64, error)
- func (c *RedisClient) HSet(ctx context.Context, key, field string, value interface{}) error
- func (c *RedisClient) Incr(ctx context.Context, key string) (int64, error)
- func (c *RedisClient) IncrBy(ctx context.Context, key string, value int64) (int64, error)
- func (c *RedisClient) LLen(ctx context.Context, key string) (int64, error)
- func (c *RedisClient) LPop(ctx context.Context, key string) (string, error)
- func (c *RedisClient) LPush(ctx context.Context, key string, values ...interface{}) (int64, error)
- func (c *RedisClient) LRange(ctx context.Context, key string, start, stop int64) ([]string, error)
- func (r *RedisClient) MGet(ctx context.Context, keys ...string) (map[string]any, error)
- func (r *RedisClient) MSet(ctx context.Context, value map[string]any, expire time.Duration) error
- func (r *RedisClient) Nil() error
- func (c *RedisClient) Ping(ctx context.Context) (string, error)
- func (c *RedisClient) Pipeline() redis.Pipeliner
- func (c *RedisClient) Publish(ctx context.Context, channel string, message interface{}) (int64, error)
- func (c *RedisClient) RPop(ctx context.Context, key string) (string, error)
- func (c *RedisClient) RPush(ctx context.Context, key string, values ...interface{}) (int64, error)
- func (c *RedisClient) SAdd(ctx context.Context, key string, members ...interface{}) (int64, error)
- func (c *RedisClient) SCard(ctx context.Context, key string) (int64, error)
- func (c *RedisClient) SIsMember(ctx context.Context, key string, member interface{}) (bool, error)
- func (c *RedisClient) SMembers(ctx context.Context, key string) ([]string, error)
- func (c *RedisClient) SRem(ctx context.Context, key string, members ...interface{}) (int64, error)
- func (c *RedisClient) ScriptLoad(ctx context.Context, script string) (string, error)
- func (c *RedisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
- func (r *RedisClient) SetEX(ctx context.Context, key string, value any, expire time.Duration) error
- func (r *RedisClient) SetNX(ctx context.Context, key string, value any, expire time.Duration) (val bool, err error)
- func (c *RedisClient) SetObject(ctx context.Context, key string, value interface{}, expiration time.Duration) error
- func (r *RedisClient) SetXX(ctx context.Context, key string, value any, expire time.Duration) (val bool, err error)
- func (c *RedisClient) Subscribe(ctx context.Context, channels ...string) *redis.PubSub
- func (c *RedisClient) TTL(ctx context.Context, key string) (time.Duration, error)
- func (c *RedisClient) TxPipeline() redis.Pipeliner
- func (c *RedisClient) UniversalClient() redis.UniversalClient
- func (c *RedisClient) Watch(ctx context.Context, fn func(*redis.Tx) error, keys ...string) error
- func (c *RedisClient) ZAdd(ctx context.Context, key string, members ...redis.Z) (int64, error)
- func (c *RedisClient) ZCard(ctx context.Context, key string) (int64, error)
- func (c *RedisClient) ZRange(ctx context.Context, key string, start, stop int64) ([]string, error)
- func (c *RedisClient) ZRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)
- func (c *RedisClient) ZRank(ctx context.Context, key, member string) (int64, error)
- func (c *RedisClient) ZRem(ctx context.Context, key string, members ...interface{}) (int64, error)
- func (c *RedisClient) ZScore(ctx context.Context, key, member string) (float64, error)
- type RedisConsumer
- type RedisPublisher
- type Task
- type TaskHandler
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CacheWrap ¶
func CacheWrap[T any]( w *CacheWrapper, fn func(context.Context) (T, error), opts ...CacheFuncOption, ) func(context.Context) (T, error)
Typed wrappers (clean and safe)
func CacheWrap1 ¶
func CacheWrap1[T, A any]( w *CacheWrapper, fn func(context.Context, A) (T, error), opts ...CacheFuncOption, ) func(context.Context, A) (T, error)
func CacheWrap2 ¶
func CacheWrap2[T, A, B any]( w *CacheWrapper, fn func(context.Context, A, B) (T, error), opts ...CacheFuncOption, ) func(context.Context, A, B) (T, error)
func CacheWrap3 ¶
func CacheWrap3[T, A, B, C any]( w *CacheWrapper, fn func(context.Context, A, B, C) (T, error), opts ...CacheFuncOption, ) func(context.Context, A, B, C) (T, error)
func CacheWrap4 ¶
func CacheWrap4[T, A, B, C, D any]( w *CacheWrapper, fn func(context.Context, A, B, C, D) (T, error), opts ...CacheFuncOption, ) func(context.Context, A, B, C, D) (T, error)
func InitDefault ¶
func InitDefault(opts ...Option)
InitDefault initializes the default package-level client.
func UnmarshalPayloadTyped ¶
UnmarshalPayloadTyped unmarshals the payload into a specific type
Types ¶
type BloomFilter ¶
type BloomFilter struct {
// contains filtered or unexported fields
}
BloomFilter represents a probabilistic data structure using Redis.
func NewBloomFilter ¶
func NewBloomFilter(client *RedisClient, key string) *BloomFilter
NewBloomFilter creates a new bloom filter.
func (*BloomFilter) Add ¶
Add adds an item to the bloom filter. Returns true if the item might have already been in the filter, false otherwise.
type Broadcaster ¶
type Broadcaster struct {
// contains filtered or unexported fields
}
func NewBroadcaster ¶
func NewBroadcaster(opts ...BroadcasterOption) (*Broadcaster, error)
func (*Broadcaster) PublishSimple ¶
func (b *Broadcaster) PublishSimple(channel string, payload interface{}) error
func (*Broadcaster) RegisterHandler ¶
func (b *Broadcaster) RegisterHandler(messageType string, handler TaskHandler) error
func (*Broadcaster) RegisterHandlerFunc ¶
func (*Broadcaster) Shutdown ¶
func (b *Broadcaster) Shutdown()
type BroadcasterConfig ¶
type BroadcasterConfig struct {
// contains filtered or unexported fields
}
type BroadcasterOption ¶
type BroadcasterOption func(*BroadcasterConfig)
func WithChannel ¶
func WithChannel(channel string) BroadcasterOption
func WithClient ¶
func WithClient(redisCli *RedisClient) BroadcasterOption
type CacheFuncOption ¶
type CacheFuncOption func(*CacheFuncOptions)
CacheFuncOption is a functional option for CacheFuncOptions
func WithDisabled ¶
func WithDisabled(disabled bool) CacheFuncOption
func WithKey ¶
func WithKey(key string) CacheFuncOption
func WithKeyGenerator ¶
func WithKeyGenerator(gen func(ctx context.Context, args ...interface{}) string) CacheFuncOption
func WithKeyPrefix ¶
func WithKeyPrefix(prefix string) CacheFuncOption
func WithRedisClient ¶
func WithRedisClient(client *RedisClient) CacheFuncOption
func WithTTL ¶
func WithTTL(ttl time.Duration) CacheFuncOption
type CacheFuncOptions ¶
type CacheFuncOptions struct {
TTL time.Duration
KeyPrefix string
Key string
KeyGenerator func(ctx context.Context, args ...interface{}) string
InternalCache cache.Cache
RedisClient *RedisClient
Disabled bool
}
CacheFuncOptions for the wrapped function
func DefaultCacheFuncOptions ¶
func DefaultCacheFuncOptions() *CacheFuncOptions
func (*CacheFuncOptions) Clone ¶
func (c *CacheFuncOptions) Clone() *CacheFuncOptions
type CacheStats ¶
CacheStats holds statistics about cache operations
func (CacheStats) String ¶
func (s CacheStats) String() string
type CacheWrapper ¶
type CacheWrapper struct {
// contains filtered or unexported fields
}
CacheWrapper provides a way to wrap functions with caching capabilities
func NewCacheWrapper ¶
func NewCacheWrapper(opts ...CacheFuncOption) *CacheWrapper
func (*CacheWrapper) Close ¶
func (w *CacheWrapper) Close()
Close properly cleans up resources used by the CacheWrapper
func (*CacheWrapper) GetStats ¶
func (w *CacheWrapper) GetStats() CacheStats
GetStats returns current cache stats
func (*CacheWrapper) ResetCacheByBaseKey ¶
func (w *CacheWrapper) ResetCacheByBaseKey(ctx context.Context, baseKey string) error
ResetCacheByBaseKey removes all cached entries associated with the given baseKey
func (*CacheWrapper) ResetCacheByKey ¶
func (w *CacheWrapper) ResetCacheByKey(ctx context.Context, key string) error
ResetCacheByKey removes the cached result for a specific key
func (*CacheWrapper) Set ¶
func (w *CacheWrapper) Set(ctx context.Context, key string, value any, opts ...CacheFuncOption) error
func (*CacheWrapper) WrapFunc ¶
func (w *CacheWrapper) WrapFunc(fn interface{}, opts ...CacheFuncOption) interface{}
WrapFunc wraps a function with caching (low-level, interface{})
type Config ¶
type Config struct {
// Mode specifies the Redis connection mode (standalone, cluster, or sentinel).
Mode Mode
// Common options
// Password is the password for the Redis server.
Password string
// DB is the database to select (not used in cluster mode).
DB int
// PoolSize is the maximum number of socket connections.
PoolSize int
// MinIdleConns is the minimum number of idle connections.
MinIdleConns int
// DialTimeout is the timeout for establishing new connections.
DialTimeout time.Duration
// ReadTimeout is the timeout for socket reads.
ReadTimeout time.Duration
// WriteTimeout is the timeout for socket writes.
WriteTimeout time.Duration
// PoolTimeout is the timeout for getting a connection from the pool.
PoolTimeout time.Duration
// IdleTimeout is the timeout for idle connections.
IdleTimeout time.Duration
// MaxRetries is the maximum number of retries before giving up.
MaxRetries int
// MinRetryBackoff is the minimum backoff between each retry.
MinRetryBackoff time.Duration
// MaxRetryBackoff is the maximum backoff between each retry.
MaxRetryBackoff time.Duration
// Standalone options
// Addr is the address of the Redis server (used in standalone mode).
Addr string
// Cluster options
// Addrs is a list of Redis cluster node addresses (used in cluster mode).
Addrs []string
// MaxRedirects is the maximum number of redirects to follow (used in cluster mode).
MaxRedirects int
// RouteByLatency enables routing read-only commands to the closest master or replica node (used in cluster mode).
RouteByLatency bool
// RouteRandomly enables routing read-only commands to random nodes (used in cluster mode).
RouteRandomly bool
// Sentinel options
// MasterName is the name of the master node (used in sentinel mode).
MasterName string
// SentinelAddrs is a list of Redis sentinel addresses (used in sentinel mode).
SentinelAddrs []string
// SentinelPassword is the password for the sentinel servers (used in sentinel mode).
SentinelPassword string
}
Config holds the configuration for the Redis client.
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a default configuration for the Redis client.
type Counter ¶
type Counter struct {
// contains filtered or unexported fields
}
Counter represents a distributed counter using Redis.
func NewCounter ¶
func NewCounter(client *RedisClient, key string) *Counter
NewCounter creates a new distributed counter.
type DLockOption ¶
type DLockOption func(*DistLockManager)
Option configures the DistLockManager.
func WithCacheSize ¶
func WithCacheSize(size int) DLockOption
WithCacheSize sets the max number of cached mutexes (default: 1000).
func WithRetryDelay ¶
func WithRetryDelay(delay time.Duration) DLockOption
WithRetryDelay sets the retry delay for redsync.
func WithTries ¶
func WithTries(tries int) DLockOption
WithTries sets the max number of attempts to acquire the lock.
type DistLock ¶
type DistLock struct {
// contains filtered or unexported fields
}
DistLock is a wrapper that ensures safe unlock and provides metadata.
func (*DistLock) IsLocked ¶
IsLocked checks if the lock is still held (best-effort, not 100% reliable).
type DistLockManager ¶
type DistLockManager struct {
// contains filtered or unexported fields
}
DistLockManager manages distributed locks with caching and config options.
func NewLockManager ¶
func NewLockManager(client *RedisClient, opts ...DLockOption) (*DistLockManager, error)
NewLockManager creates a new distributed lock manager. It uses an LRU cache to avoid infinite growth of mutex entries.
func (*DistLockManager) GetLock ¶
func (lm *DistLockManager) GetLock(key string) *redsync.Mutex
GetLock returns a redsync.Mutex for the given key. It caches the mutex instance to avoid recreation. Not goroutine-safe for the same key's mutex usage (caller must manage).
func (*DistLockManager) Lock ¶
func (lm *DistLockManager) Lock(ctx context.Context, key string, opts ...LockOption) (*DistLock, error)
Lock acquires the lock with a timeout and returns a wrapper for safe unlock. This is the recommended way to use the lock.
type DistributedScheduler ¶
type DistributedScheduler struct {
// contains filtered or unexported fields
}
DistributedScheduler 分布式调度器
func NewDistributedScheduler ¶
func NewDistributedScheduler(locker *DistLockManager, instanceID string) *DistributedScheduler
NewDistributedScheduler 创建调度器 注意:DistLockManager 应由外部创建并注入
func (*DistributedScheduler) AddTask ¶
func (s *DistributedScheduler) AddTask(task *Task) (cron.EntryID, error)
AddTask 添加一个分布式任务
func (*DistributedScheduler) ListTasks ¶
func (s *DistributedScheduler) ListTasks() map[string]string
ListTasks 获取所有任务
func (*DistributedScheduler) RemoveTask ¶
func (s *DistributedScheduler) RemoveTask(taskID string) bool
RemoveTask 删除任务
func (*DistributedScheduler) StopRunningTask ¶
func (s *DistributedScheduler) StopRunningTask(taskID string) bool
StopRunningTask 取消正在运行的任务
type HandlerFunc ¶
HandlerFunc is a function type that implements TaskHandler (duplicated from consume.go for Redis implementation)
func (HandlerFunc) ProcessTask ¶
func (f HandlerFunc) ProcessTask(ctx context.Context, payload []byte) error
ProcessTask calls the HandlerFunc
type KeyConfig ¶
type KeyConfig struct {
Expire time.Duration `json:"expire"`
MaxRecords int64 `json:"max_records"`
}
KeyConfig stores configuration for a key.
type KeyNotConfiguredError ¶
type KeyNotConfiguredError struct {
Key string
}
KeyNotConfiguredError is returned when a key is not configured.
func (*KeyNotConfiguredError) Error ¶
func (e *KeyNotConfiguredError) Error() string
type LocalConsumer ¶
type LocalConsumer struct {
// contains filtered or unexported fields
}
LocalConsumer represents a local pub/sub consumer
func NewLocalConsumer ¶
func NewLocalConsumer(publisher *LocalPublisher, channel ...string) *LocalConsumer
NewLocalConsumer creates a new local consumer
func (*LocalConsumer) RegisterHandler ¶
func (c *LocalConsumer) RegisterHandler(messageType string, handler TaskHandler) error
RegisterHandler registers a handler for a specific message type
func (*LocalConsumer) RegisterHandlerFunc ¶
func (c *LocalConsumer) RegisterHandlerFunc(messageType string, handlerFunc func(ctx context.Context, payload []byte) error) error
RegisterHandlerFunc registers a handler function for a specific message type
func (*LocalConsumer) Shutdown ¶
func (c *LocalConsumer) Shutdown()
Shutdown gracefully shuts down the consumer
type LocalMessage ¶
type LocalMessage struct {
Type string `json:"type"`
Payload json.RawMessage `json:"payload"`
}
LocalMessage represents a message in the local pub/sub system
type LocalPublisher ¶
type LocalPublisher struct {
// contains filtered or unexported fields
}
LocalPublisher represents a local pub/sub publisher
func NewLocalPublisher ¶
func NewLocalPublisher(channel ...string) *LocalPublisher
NewLocalPublisher creates a new local publisher
func (*LocalPublisher) Close ¶
func (p *LocalPublisher) Close() error
Close closes the local publisher
func (*LocalPublisher) PublishSimple ¶
func (p *LocalPublisher) PublishSimple(channel string, payload interface{}) error
PublishSimple publishes a message to a local channel
func (*LocalPublisher) Subscribe ¶
func (p *LocalPublisher) Subscribe(ch chan LocalMessage)
Subscribe adds a listener for the specified channel
func (*LocalPublisher) Unsubscribe ¶
func (p *LocalPublisher) Unsubscribe(ch chan LocalMessage)
Unsubscribe removes a listener for the specified channel
type LockOption ¶
type LockOption func(*lockConfig)
LockOption allows per-lock configuration.
func WithLockTimeout ¶
func WithLockTimeout(timeout time.Duration) LockOption
WithLockTimeout sets the maximum time to wait for acquiring the lock.
type Option ¶
type Option func(*Config)
Option defines a function that configures the Redis client.
func WithDialTimeout ¶
WithDialTimeout sets the timeout for establishing new connections.
func WithIdleTimeout ¶
WithIdleTimeout sets the timeout for idle connections.
func WithMasterName ¶
WithMasterName sets the name of the master node for sentinel mode.
func WithMaxRedirects ¶
WithMaxRedirects sets the maximum number of redirects to follow.
func WithMaxRetries ¶
WithMaxRetries sets the maximum number of retries before giving up.
func WithMaxRetryBackoff ¶
WithMaxRetryBackoff sets the maximum backoff between each retry.
func WithMinIdleConns ¶
WithMinIdleConns sets the minimum number of idle connections.
func WithMinRetryBackoff ¶
WithMinRetryBackoff sets the minimum backoff between each retry.
func WithPassword ¶
WithPassword sets the Redis server password.
func WithPoolSize ¶
WithPoolSize sets the maximum number of socket connections.
func WithPoolTimeout ¶
WithPoolTimeout sets the timeout for getting a connection from the pool.
func WithReadTimeout ¶
WithReadTimeout sets the timeout for socket reads.
func WithRouteByLatency ¶
WithRouteByLatency enables routing read-only commands to the closest master or replica node.
func WithRouteRandomly ¶
WithRouteRandomly enables routing read-only commands to random nodes.
func WithSentinelAddrs ¶
WithSentinelAddrs sets the Redis sentinel addresses.
func WithSentinelPassword ¶
WithSentinelPassword sets the password for the sentinel servers.
func WithWriteTimeout ¶
WithWriteTimeout sets the timeout for socket writes.
type PubSub ¶
type PubSub struct {
// contains filtered or unexported fields
}
PubSub represents a publish/subscribe system using Redis.
func NewPubSub ¶
func NewPubSub(client *RedisClient) *PubSub
NewPubSub creates a new publish/subscribe system.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter represents a rate limiter using Redis.
func NewRateLimiter ¶
func NewRateLimiter(client *RedisClient, key string, limit int, window time.Duration) *RateLimiter
NewRateLimiter creates a new rate limiter.
type RecordStore ¶
type RecordStore[T any] struct { // contains filtered or unexported fields }
RecordStore is a generic in-memory store for time-series records.
func NewRecordStore ¶
func NewRecordStore[T any](client *RedisClient, namespace string) *RecordStore[T]
NewR'e'a'co'r'dStore creates a new RecordStore instance.
func (*RecordStore[T]) CreateKey ¶
func (ms *RecordStore[T]) CreateKey(ctx context.Context, key string, expire time.Duration, maxRecords int64) error
CreateKey creates a new key with config (idempotent). Uses SETNX to prevent race conditions in multi-instance environments.
func (*RecordStore[T]) GetLatestRecords ¶
func (ms *RecordStore[T]) GetLatestRecords(ctx context.Context, key string, count int64) ([]Record[T], error)
GetLatestRecords retrieves the latest N records.
func (*RecordStore[T]) GetRecordCount ¶
GetRecordCount returns the number of records for a key.
func (*RecordStore[T]) IsKeyCreated ¶
IsKeyCreated checks if the key has been created (i.e., config exists). Uses local cache for performance.
func (*RecordStore[T]) SetConfigCacheTTL ¶
func (ms *RecordStore[T]) SetConfigCacheTTL(ttl time.Duration)
SetConfigCacheTTL sets the TTL for config cache.
func (*RecordStore[T]) WriteRecord ¶
func (ms *RecordStore[T]) WriteRecord(ctx context.Context, key string, data T) error
WriteRecord writes a new record to the key.
type RedisClient ¶
type RedisClient struct {
// contains filtered or unexported fields
}
RedisClient is a wrapper around the Redis client.
func New ¶
func New(opts ...Option) *RedisClient
New creates a new RedisClient instance with the given options.
func (*RedisClient) Client ¶
func (c *RedisClient) Client() *redis.Client
Client returns the underlying Redis client.
func (*RedisClient) Close ¶
func (c *RedisClient) Close() error
Close closes the client, releasing any open resources.
func (*RedisClient) Eval ¶
func (c *RedisClient) Eval(ctx context.Context, script string, keys []string, args ...interface{}) (interface{}, error)
Eval evaluates a Lua script.
func (*RedisClient) Expire ¶
func (c *RedisClient) Expire(ctx context.Context, key string, expiration time.Duration) (bool, error)
Expire sets the expiration for a key.
func (*RedisClient) GetObject ¶
func (c *RedisClient) GetObject(ctx context.Context, key string, value interface{}) error
GetObject gets the value of a key and unmarshals it into the given object.
func (*RedisClient) HExists ¶
HExists returns if field is an existing field in the hash stored at key.
func (*RedisClient) HSet ¶
func (c *RedisClient) HSet(ctx context.Context, key, field string, value interface{}) error
HSet sets field in the hash stored at key to value.
func (*RedisClient) LPush ¶
LPush inserts all the specified values at the head of the list stored at key.
func (*RedisClient) Nil ¶
func (r *RedisClient) Nil() error
func (*RedisClient) Ping ¶
func (c *RedisClient) Ping(ctx context.Context) (string, error)
Ping pings the Redis server.
func (*RedisClient) Pipeline ¶
func (c *RedisClient) Pipeline() redis.Pipeliner
Pipeline creates a new pipeline.
func (*RedisClient) Publish ¶
func (c *RedisClient) Publish(ctx context.Context, channel string, message interface{}) (int64, error)
Publish publishes a message to the specified channel.
func (*RedisClient) RPush ¶
RPush inserts all the specified values at the tail of the list stored at key.
func (*RedisClient) SCard ¶
SCard returns the set cardinality (number of elements) of the set stored at key.
func (*RedisClient) ScriptLoad ¶
ScriptLoad loads a Lua script into the scripts cache.
func (*RedisClient) Set ¶
func (c *RedisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
Set sets the value of a key.
func (*RedisClient) SetObject ¶
func (c *RedisClient) SetObject(ctx context.Context, key string, value interface{}, expiration time.Duration) error
SetObject sets the value of a key to the marshaled object.
func (*RedisClient) TxPipeline ¶
func (c *RedisClient) TxPipeline() redis.Pipeliner
TxPipeline creates a new transaction pipeline.
func (*RedisClient) UniversalClient ¶
func (c *RedisClient) UniversalClient() redis.UniversalClient
UniversalClient returns the underlying universal Redis client.
func (*RedisClient) Watch ¶
Watch watches the given keys to determine execution of the MULTI/EXEC block.
func (*RedisClient) ZAdd ¶
ZAdd adds one or more members to a sorted set, or updates its score if it already exists.
func (*RedisClient) ZCard ¶
ZCard returns the sorted set cardinality (number of elements) of the sorted set stored at key.
func (*RedisClient) ZRangeWithScores ¶
func (c *RedisClient) ZRangeWithScores(ctx context.Context, key string, start, stop int64) ([]redis.Z, error)
ZRangeWithScores returns a range of members with scores in a sorted set, by index.
func (*RedisClient) ZRank ¶
ZRank returns the rank of member in the sorted set stored at key, with the scores ordered from low to high.
type RedisConsumer ¶
type RedisConsumer struct {
// contains filtered or unexported fields
}
RedisConsumer represents a Redis pub/sub consumer
func NewRedisConsumer ¶
func NewRedisConsumer(redisCli *RedisClient, channel ...string) (*RedisConsumer, error)
NewRedisConsumerWithConfig creates a new Redis consumer using application configuration
func (*RedisConsumer) RegisterHandler ¶
func (c *RedisConsumer) RegisterHandler(messageType string, handler TaskHandler) error
RegisterHandler registers a handler for a specific message type
func (*RedisConsumer) RegisterHandlerFunc ¶
func (c *RedisConsumer) RegisterHandlerFunc(messageType string, handlerFunc func(ctx context.Context, payload []byte) error) error
RegisterHandlerFunc registers a handler function for a specific message type
func (*RedisConsumer) Shutdown ¶
func (c *RedisConsumer) Shutdown()
Shutdown gracefully shuts down the consumer
type RedisPublisher ¶
type RedisPublisher struct {
// contains filtered or unexported fields
}
RedisPublisher represents a Redis pub/sub publisher
func NewRedisPublisher ¶
func NewRedisPublisher(redisCli *RedisClient, channel ...string) (*RedisPublisher, error)
NewRedisPublisher creates a new Redis publisher using application configuration
func (*RedisPublisher) Close ¶
func (p *RedisPublisher) Close() error
Close closes the Redis client connection
func (*RedisPublisher) PublishSimple ¶
func (p *RedisPublisher) PublishSimple(channel string, payload interface{}) error
PublishSimple publishes a message to a Redis channel with default options