Documentation
¶
Index ¶
- Variables
- func IsCacheDisabled(err error) bool
- func IsConnectionFailed(err error) bool
- func IsKeyNotFound(err error) bool
- type CacheStrategy
- type ClusterConfig
- type Config
- type InvalidationConfig
- type InvalidationStrategy
- type LargeValueConfig
- type LoggingConfig
- type Manager
- func (m *Manager) AddDependency(ctx context.Context, entityType string, entityID interface{}, cacheKey string) error
- func (m *Manager) AddMultipleDependencies(ctx context.Context, dependencies map[string][]interface{}, cacheKey string) error
- func (m *Manager) Close() error
- func (m *Manager) Config() *Config
- func (m *Manager) Delete(ctx context.Context, key string) error
- func (m *Manager) DeleteKeys(ctx context.Context, keys []string) error
- func (m *Manager) DeleteLarge(ctx context.Context, key string) error
- func (m *Manager) Exists(ctx context.Context, key string) (bool, error)
- func (m *Manager) Get(ctx context.Context, key string) ([]byte, error)
- func (m *Manager) GetDependencies(ctx context.Context, entityType string, entityID interface{}) ([]string, error)
- func (m *Manager) GetJSON(ctx context.Context, key string, target interface{}) error
- func (m *Manager) GetLarge(ctx context.Context, key string) ([]byte, error)
- func (m *Manager) GetLargeJSON(ctx context.Context, key string, target interface{}) error
- func (m *Manager) GetMetrics() MetricsSnapshot
- func (m *Manager) GetStats(ctx context.Context) (map[string]interface{}, error)
- func (m *Manager) InvalidateEntityDependencies(ctx context.Context, entityType string, entityID interface{}) error
- func (m *Manager) InvalidatePattern(ctx context.Context, pattern string) error
- func (m *Manager) InvalidateRelationships(ctx context.Context, entityType string, entityID interface{}) error
- func (m *Manager) Ping(ctx context.Context) error
- func (m *Manager) ResetMetrics()
- func (m *Manager) Set(ctx context.Context, key string, value []byte) error
- func (m *Manager) SetJSON(ctx context.Context, key string, value interface{}) error
- func (m *Manager) SetJSONWithDependencies(ctx context.Context, cacheKey string, value interface{}, ...) error
- func (m *Manager) SetLarge(ctx context.Context, key string, value []byte) error
- func (m *Manager) SetLargeJSON(ctx context.Context, key string, value interface{}) error
- func (m *Manager) SetLargeWithDependencies(ctx context.Context, cacheKey string, value []byte, ...) error
- func (m *Manager) SetWithDependencies(ctx context.Context, cacheKey string, value []byte, ...) error
- func (m *Manager) SetWithTTL(ctx context.Context, key string, value []byte, ttl time.Duration) error
- func (m *Manager) WarmCache(ctx context.Context, entities []string) error
- type Metrics
- func (m *Metrics) GetSnapshot() MetricsSnapshot
- func (m *Metrics) RecordCacheError()
- func (m *Metrics) RecordCacheHit()
- func (m *Metrics) RecordCacheMiss()
- func (m *Metrics) RecordChunked()
- func (m *Metrics) RecordCompression(bytesSaved uint64)
- func (m *Metrics) RecordDelete(duration time.Duration)
- func (m *Metrics) RecordDependency()
- func (m *Metrics) RecordGet(duration time.Duration)
- func (m *Metrics) RecordInvalidation()
- func (m *Metrics) RecordSet(duration time.Duration)
- func (m *Metrics) Reset()
- type MetricsSnapshot
- type WarmUpConfig
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCacheDisabled is returned when attempting operations on a disabled cache ErrCacheDisabled = errors.New("redis cache is disabled") // ErrClientNotInitialized is returned when the Redis client is nil ErrClientNotInitialized = errors.New("redis client not initialized") // ErrKeyNotFound is returned when a cache key doesn't exist (not an error condition) ErrKeyNotFound = errors.New("cache key not found") // ErrConnectionFailed is returned when Redis connection cannot be established ErrConnectionFailed = errors.New("redis connection failed") // ErrInvalidKey is returned for invalid cache key operations ErrInvalidKey = errors.New("invalid cache key") // ErrSerializationFailed is returned when JSON marshaling/unmarshaling fails ErrSerializationFailed = errors.New("cache serialization failed") )
Sentinel errors for Redis operations
Functions ¶
func IsCacheDisabled ¶
IsCacheDisabled checks if an error is ErrCacheDisabled
func IsConnectionFailed ¶
IsConnectionFailed checks if an error is ErrConnectionFailed
func IsKeyNotFound ¶
IsKeyNotFound checks if an error is ErrKeyNotFound
Types ¶
type CacheStrategy ¶
type CacheStrategy string
Cache strategy enums
const ( CacheStrategyReadThrough CacheStrategy = "read_through" CacheStrategyWriteThrough CacheStrategy = "write_through" CacheStrategyWriteBehind CacheStrategy = "write_behind" CacheStrategyLazyLoading CacheStrategy = "lazy_loading" )
type ClusterConfig ¶
type ClusterConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Addresses []string `json:"addresses" yaml:"addresses"`
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
}
ClusterConfig for Redis Cluster setup
type Config ¶
type Config struct {
// Cache Strategy
Enabled bool `json:"enabled" yaml:"enabled"`
Strategy CacheStrategy `json:"strategy" yaml:"strategy"` // read_through, write_through, write_behind
DefaultTTL time.Duration `json:"default_ttl" yaml:"default_ttl"`
NullCacheTTL time.Duration `json:"null_cache_ttl" yaml:"null_cache_ttl"` // Cache null results
// Redis Connection
Host string `json:"host" yaml:"host"`
Port int `json:"port" yaml:"port"`
Password string `json:"password" yaml:"password"`
Database int `json:"database" yaml:"database"`
// Connection Pool
PoolSize int `json:"pool_size" yaml:"pool_size"`
MinIdleConns int `json:"min_idle_conns" yaml:"min_idle_conns"`
MaxConnAge time.Duration `json:"max_conn_age" yaml:"max_conn_age"`
PoolTimeout time.Duration `json:"pool_timeout" yaml:"pool_timeout"`
IdleTimeout time.Duration `json:"idle_timeout" yaml:"idle_timeout"`
IdleCheckFrequency time.Duration `json:"idle_check_frequency" yaml:"idle_check_frequency"`
// Performance
ReadTimeout time.Duration `json:"read_timeout" yaml:"read_timeout"`
WriteTimeout time.Duration `json:"write_timeout" yaml:"write_timeout"`
DialTimeout time.Duration `json:"dial_timeout" yaml:"dial_timeout"`
// Clustering (for Redis Cluster)
Cluster ClusterConfig `json:"cluster" yaml:"cluster"`
// Cache Invalidation
Invalidation InvalidationConfig `json:"invalidation" yaml:"invalidation"`
// Cache Warming
WarmUp WarmUpConfig `json:"warm_up" yaml:"warm_up"`
// Cache Metrics
EnableMetrics bool `json:"enable_metrics" yaml:"enable_metrics"`
// Cache Logging
Logging LoggingConfig `json:"logging" yaml:"logging"`
// Large Value Handling
LargeValue LargeValueConfig `json:"large_value" yaml:"large_value"`
}
Config holds Redis cache configuration
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a Redis configuration with sensible defaults
func (*Config) IsClusterMode ¶
IsClusterMode returns true if Redis cluster is enabled
type InvalidationConfig ¶
type InvalidationConfig struct {
// Relationship Detection
AutoDetectRelationships bool `json:"auto_detect_relationships" yaml:"auto_detect_relationships"`
MaxRelationshipDepth int `json:"max_relationship_depth" yaml:"max_relationship_depth"`
IgnoreRelationships []string `json:"ignore_relationships" yaml:"ignore_relationships"`
// Invalidation Strategy
Strategy InvalidationStrategy `json:"strategy" yaml:"strategy"` // immediate, batch, async
BatchSize int `json:"batch_size" yaml:"batch_size"`
BatchFlushInterval time.Duration `json:"batch_flush_interval" yaml:"batch_flush_interval"`
// Pattern-based Invalidation
KeyPatterns map[string][]string `json:"key_patterns" yaml:"key_patterns"` // entity -> patterns to invalidate
}
InvalidationConfig controls relationship-aware cache invalidation
type InvalidationStrategy ¶
type InvalidationStrategy string
Invalidation strategy enums
const ( InvalidationImmediate InvalidationStrategy = "immediate" InvalidationBatch InvalidationStrategy = "batch" InvalidationAsync InvalidationStrategy = "async" )
type LargeValueConfig ¶
type LargeValueConfig struct {
MaxValueSize int `json:"max_value_size" yaml:"max_value_size"` // Maximum size per key (bytes)
ChunkSize int `json:"chunk_size" yaml:"chunk_size"` // Size per chunk (bytes)
CompressThreshold int `json:"compress_threshold" yaml:"compress_threshold"` // Auto-compress above this size
EnableCompression bool `json:"enable_compression" yaml:"enable_compression"` // Enable/disable compression
EnableChunking bool `json:"enable_chunking" yaml:"enable_chunking"` // Enable/disable chunking
}
LargeValueConfig controls handling of large cache values
type LoggingConfig ¶
type LoggingConfig struct {
LogCacheHits bool `json:"log_cache_hits" yaml:"log_cache_hits"`
LogCacheMisses bool `json:"log_cache_misses" yaml:"log_cache_misses"`
LogInvalidations bool `json:"log_invalidations" yaml:"log_invalidations"`
}
LoggingConfig controls Redis cache logging behavior
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages Redis connections and cache operations
func NewManager ¶
NewManager creates a new Redis cache manager
func (*Manager) AddDependency ¶
func (m *Manager) AddDependency(ctx context.Context, entityType string, entityID interface{}, cacheKey string) error
AddDependency links a cache key to an entity for relationship-aware invalidation
func (*Manager) AddMultipleDependencies ¶
func (m *Manager) AddMultipleDependencies(ctx context.Context, dependencies map[string][]interface{}, cacheKey string) error
AddMultipleDependencies links a cache key to multiple entities dependencies: map[entityType] -> []entityIDs
func (*Manager) DeleteKeys ¶
DeleteKeys removes multiple keys from cache
func (*Manager) DeleteLarge ¶
DeleteLarge deletes large values including all chunks and metadata
func (*Manager) GetDependencies ¶
func (m *Manager) GetDependencies(ctx context.Context, entityType string, entityID interface{}) ([]string, error)
GetDependencies returns all cache keys that depend on an entity
func (*Manager) GetLarge ¶
GetLarge retrieves large values, handling decompression and chunk reassembly
func (*Manager) GetLargeJSON ¶
GetLargeJSON retrieves and unmarshals large JSON values
func (*Manager) GetMetrics ¶
func (m *Manager) GetMetrics() MetricsSnapshot
GetMetrics returns current cache performance metrics
func (*Manager) InvalidateEntityDependencies ¶
func (m *Manager) InvalidateEntityDependencies(ctx context.Context, entityType string, entityID interface{}) error
InvalidateEntityDependencies clears all caches that depend on a specific entity
func (*Manager) InvalidatePattern ¶
InvalidatePattern removes keys matching a pattern using SCAN instead of KEYS SCAN is non-blocking and production-safe, unlike KEYS which blocks the Redis server
func (*Manager) InvalidateRelationships ¶
func (m *Manager) InvalidateRelationships(ctx context.Context, entityType string, entityID interface{}) error
InvalidateRelationships invalidates related cache keys based on entity relationships
func (*Manager) Ping ¶
Ping tests the Redis connection Returns nil if cache is disabled (not an error condition) Returns ErrClientNotInitialized if client is not initialized Returns ErrConnectionFailed if ping fails
func (*Manager) ResetMetrics ¶
func (m *Manager) ResetMetrics()
ResetMetrics resets all performance metrics counters
func (*Manager) SetJSONWithDependencies ¶
func (m *Manager) SetJSONWithDependencies(ctx context.Context, cacheKey string, value interface{}, dependencies map[string][]interface{}) error
SetJSONWithDependencies stores JSON value and registers its dependencies
func (*Manager) SetLargeJSON ¶
SetLargeJSON stores large JSON values with compression and chunking
func (*Manager) SetLargeWithDependencies ¶
func (m *Manager) SetLargeWithDependencies(ctx context.Context, cacheKey string, value []byte, dependencies map[string][]interface{}) error
SetLargeWithDependencies stores a large value and registers its dependencies
func (*Manager) SetWithDependencies ¶
func (m *Manager) SetWithDependencies(ctx context.Context, cacheKey string, value []byte, dependencies map[string][]interface{}) error
SetWithDependencies stores a value and registers its dependencies in one operation
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics tracks cache performance statistics
func (*Metrics) GetSnapshot ¶
func (m *Metrics) GetSnapshot() MetricsSnapshot
GetSnapshot returns a snapshot of current metrics
func (*Metrics) RecordCacheError ¶
func (m *Metrics) RecordCacheError()
RecordCacheError increments cache error counter
func (*Metrics) RecordCacheHit ¶
func (m *Metrics) RecordCacheHit()
RecordCacheHit increments cache hit counter
func (*Metrics) RecordCacheMiss ¶
func (m *Metrics) RecordCacheMiss()
RecordCacheMiss increments cache miss counter
func (*Metrics) RecordChunked ¶
func (m *Metrics) RecordChunked()
RecordChunked increments chunked operation counter
func (*Metrics) RecordCompression ¶
RecordCompression records bytes saved via compression
func (*Metrics) RecordDelete ¶
RecordDelete records a delete operation with latency
func (*Metrics) RecordDependency ¶
func (m *Metrics) RecordDependency()
RecordDependency increments dependency counter
func (*Metrics) RecordInvalidation ¶
func (m *Metrics) RecordInvalidation()
RecordInvalidation increments invalidation counter
type MetricsSnapshot ¶
type MetricsSnapshot struct {
// Cache metrics
CacheHits uint64
CacheMisses uint64
CacheErrors uint64
CacheHitRate float64 // Percentage
// Operation counts
GetOperations uint64
SetOperations uint64
DeleteOperations uint64
// Latency metrics
AvgGetLatency time.Duration
AvgSetLatency time.Duration
AvgDeleteLatency time.Duration
// Large value metrics
CompressionBytesSaved uint64
ChunkedOperations uint64
// Invalidation metrics
InvalidationCount uint64
DependencyCount uint64
}
MetricsSnapshot represents a point-in-time snapshot of metrics
type WarmUpConfig ¶
type WarmUpConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Strategies []string `json:"strategies" yaml:"strategies"` // startup, schedule, on_demand
// Scheduled warming
CronExpression string `json:"cron_expression" yaml:"cron_expression"`
WarmUpTimeout time.Duration `json:"warm_up_timeout" yaml:"warm_up_timeout"`
// Entities to warm
Entities []string `json:"entities" yaml:"entities"`
}
WarmUpConfig controls cache warming strategies