redis

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

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

func IsCacheDisabled(err error) bool

IsCacheDisabled checks if an error is ErrCacheDisabled

func IsConnectionFailed

func IsConnectionFailed(err error) bool

IsConnectionFailed checks if an error is ErrConnectionFailed

func IsKeyNotFound

func IsKeyNotFound(err error) bool

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"`

	// Serialization Format
	// msgpack: 5-10x faster than JSON, smaller payload (recommended for production)
	// json: Human-readable, easier debugging (good for development)
	SerializationFormat SerializationFormat `json:"serialization_format" yaml:"serialization_format"`

	// 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) GetAddr

func (c *Config) GetAddr() string

GetAddr returns the Redis connection address

func (*Config) IsClusterMode

func (c *Config) IsClusterMode() bool

IsClusterMode returns true if Redis cluster is enabled

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the Redis configuration is valid

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

func NewManager(config *Config) (*Manager, error)

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

func (m *Manager) Close() error

Close closes the Redis connection

func (*Manager) Config

func (m *Manager) Config() *Config

Config returns the manager's configuration

func (*Manager) Delete

func (m *Manager) Delete(ctx context.Context, key string) error

Delete removes a key from cache

func (*Manager) DeleteKeys

func (m *Manager) DeleteKeys(ctx context.Context, keys []string) error

DeleteKeys removes multiple keys from cache

func (*Manager) DeleteLarge

func (m *Manager) DeleteLarge(ctx context.Context, key string) error

DeleteLarge deletes large values including all chunks and metadata

func (*Manager) Exists

func (m *Manager) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists in cache

func (*Manager) Get

func (m *Manager) Get(ctx context.Context, key string) ([]byte, error)

Get retrieves a value from cache

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

func (m *Manager) GetLarge(ctx context.Context, key string) ([]byte, error)

GetLarge retrieves large values, handling decompression and chunk reassembly

func (*Manager) GetLargeValue added in v0.2.0

func (m *Manager) GetLargeValue(ctx context.Context, key string, target interface{}) error

GetLargeValue retrieves and unmarshals large values Uses configured serialization format (JSON or MessagePack)

func (*Manager) GetMetrics

func (m *Manager) GetMetrics() MetricsSnapshot

GetMetrics returns current cache performance metrics

func (*Manager) GetStats

func (m *Manager) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats returns Redis connection and performance statistics

func (*Manager) GetValue added in v0.2.0

func (m *Manager) GetValue(ctx context.Context, key string, target interface{}) error

GetValue retrieves and unmarshals a value from cache using the configured serialization format

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

func (m *Manager) InvalidatePattern(ctx context.Context, pattern string) error

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

func (m *Manager) Ping(ctx context.Context) error

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

func (m *Manager) Set(ctx context.Context, key string, value []byte) error

Set stores a value in cache with TTL

func (*Manager) SetLarge

func (m *Manager) SetLarge(ctx context.Context, key string, value []byte) error

SetLarge stores large values using compression and chunking if needed

func (*Manager) SetLargeValue added in v0.2.0

func (m *Manager) SetLargeValue(ctx context.Context, key string, value interface{}) error

SetLargeValue stores large values with compression and chunking Uses configured serialization format (JSON or MessagePack)

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) SetValue added in v0.2.0

func (m *Manager) SetValue(ctx context.Context, key string, value interface{}) error

SetValue stores a value in cache using the configured serialization format (JSON or MessagePack)

func (*Manager) SetValueWithDependencies added in v0.2.0

func (m *Manager) SetValueWithDependencies(ctx context.Context, cacheKey string, value interface{}, dependencies map[string][]interface{}) error

SetValueWithDependencies stores value and registers its dependencies Uses configured serialization format (JSON or MessagePack)

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

func (*Manager) SetWithTTL

func (m *Manager) SetWithTTL(ctx context.Context, key string, value []byte, ttl time.Duration) error

SetWithTTL stores a value in cache with custom TTL

func (*Manager) WarmCache

func (m *Manager) WarmCache(ctx context.Context, entities []string) error

WarmCache preloads commonly accessed data

type Metrics

type Metrics struct {
	// contains filtered or unexported fields
}

Metrics tracks cache performance statistics

func NewMetrics

func NewMetrics() *Metrics

NewMetrics creates a new metrics instance

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

func (m *Metrics) RecordCompression(bytesSaved uint64)

RecordCompression records bytes saved via compression

func (*Metrics) RecordDelete

func (m *Metrics) RecordDelete(duration time.Duration)

RecordDelete records a delete operation with latency

func (*Metrics) RecordDependency

func (m *Metrics) RecordDependency()

RecordDependency increments dependency counter

func (*Metrics) RecordGet

func (m *Metrics) RecordGet(duration time.Duration)

RecordGet records a get operation with latency

func (*Metrics) RecordInvalidation

func (m *Metrics) RecordInvalidation()

RecordInvalidation increments invalidation counter

func (*Metrics) RecordSet

func (m *Metrics) RecordSet(duration time.Duration)

RecordSet records a set operation with latency

func (*Metrics) Reset

func (m *Metrics) Reset()

Reset resets all metrics counters

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 SerializationFormat added in v0.2.0

type SerializationFormat string

Serialization format enums

const (
	SerializationJSON    SerializationFormat = "json"    // Human-readable, slower
	SerializationMsgPack SerializationFormat = "msgpack" // Binary, 5-10x faster (recommended)
)

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

Jump to

Keyboard shortcuts

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