cache

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCacheMiss indicates that a key was not found in the cache
	ErrCacheMiss = errors.New("cache miss")

	// ErrCacheConnectionFailed indicates that the cache connection failed
	ErrCacheConnectionFailed = errors.New("cache connection failed")

	// ErrInvalidCacheKey indicates that the provided cache key is invalid
	ErrInvalidCacheKey = errors.New("invalid cache key")

	// ErrCacheFull indicates that the cache is full and cannot accept more items
	ErrCacheFull = errors.New("cache is full")

	// ErrSerializationFailed indicates that serialization of the value failed
	ErrSerializationFailed = errors.New("serialization failed")

	// ErrDeserializationFailed indicates that deserialization of the value failed
	ErrDeserializationFailed = errors.New("deserialization failed")

	// ErrCacheTimeout indicates that a cache operation timed out
	ErrCacheTimeout = errors.New("cache operation timeout")
)

Cache errors

View Source
var (
	ErrCacheDisabled = fmt.Errorf("cache is disabled")
)

Cache errors

Functions

This section is empty.

Types

type BasicCacheMetrics added in v1.0.2

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

BasicCacheMetrics recolecta métricas de cache

func NewBasicCacheMetrics added in v1.0.2

func NewBasicCacheMetrics() *BasicCacheMetrics

NewBasicCacheMetrics crea un nuevo recolector de métricas

func (*BasicCacheMetrics) GetStats added in v1.0.2

func (m *BasicCacheMetrics) GetStats() map[string]interface{}

GetStats retorna todas las estadísticas

func (*BasicCacheMetrics) RecordError added in v1.0.2

func (m *BasicCacheMetrics) RecordError(operation string)

RecordError registra un error en una operación

func (*BasicCacheMetrics) RecordOperation added in v1.0.2

func (m *BasicCacheMetrics) RecordOperation(operation, key string)

RecordOperation registra una operación de cache

func (*BasicCacheMetrics) RecordOperationWithDuration added in v1.0.2

func (m *BasicCacheMetrics) RecordOperationWithDuration(operation, key string, duration time.Duration)

RecordOperationWithDuration registra una operación con duración

func (*BasicCacheMetrics) Reset added in v1.0.2

func (m *BasicCacheMetrics) Reset()

Reset resetea todas las métricas

type CacheConfig

type CacheConfig struct {
	// Redis Configuration
	RedisHost     string
	RedisPort     string
	RedisPassword string
	RedisDB       int

	// Connection Pool
	PoolSize     int
	MinIdleConns int
	MaxConnAge   time.Duration
	PoolTimeout  time.Duration
	IdleTimeout  time.Duration

	// Timeouts
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	DialTimeout  time.Duration

	// Cache Behavior
	DefaultExpiration time.Duration
	KeyPrefix         string
	EnableCompression bool
	EnableMetrics     bool

	// Fallback Settings
	EnableMemoryFallback bool
	MemoryCacheSize      int
}

CacheConfig configuración unificada de cache

func DefaultCacheConfig

func DefaultCacheConfig() *CacheConfig

DefaultCacheConfig retorna configuración por defecto

type CacheInterface

type CacheInterface interface {
	// Basic operations
	Get(ctx context.Context, key string, dest interface{}) error
	Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
	Delete(ctx context.Context, key string) error
	Exists(ctx context.Context, key string) bool

	// Advanced operations
	GetMultiple(ctx context.Context, keys []string) (map[string]interface{}, error)
	SetMultiple(ctx context.Context, items map[string]interface{}, expiration time.Duration) error
	InvalidatePattern(ctx context.Context, pattern string) error

	// Atomic operations
	SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) (bool, error)
	Increment(ctx context.Context, key string, delta int64) (int64, error)

	// Info operations
	GetTTL(ctx context.Context, key string) time.Duration
	Ping(ctx context.Context) error
	GetStats(ctx context.Context) (map[string]interface{}, error)
}

CacheInterface define la interfaz unificada de cache

type CacheKey added in v1.0.2

type CacheKey struct {
	Prefix  string
	Service string
	Entity  string
	ID      string
	Version string
	Tenant  string
	Suffix  string
}

CacheKey construye claves de cache consistentes y optimizadas

func ConfigCacheKey added in v1.0.2

func ConfigCacheKey(service, configType string, tenant ...string) CacheKey

ConfigCacheKey construye clave de cache para configuración

func QueryCacheKey added in v1.0.2

func QueryCacheKey(service, queryType, hash string, tenant ...string) CacheKey

QueryCacheKey construye clave de cache para resultados de consulta

func SessionCacheKey added in v1.0.2

func SessionCacheKey(sessionID string, tenant ...string) CacheKey

SessionCacheKey construye clave de cache para datos de sesión

func UserCacheKey added in v1.0.2

func UserCacheKey(userID, dataType string, tenant ...string) CacheKey

UserCacheKey construye clave de cache para datos de usuario

func (CacheKey) Pattern added in v1.0.2

func (ck CacheKey) Pattern() string

CachePattern genera patrones para búsqueda/eliminación masiva

func (CacheKey) String added in v1.0.2

func (ck CacheKey) String() string

String convierte CacheKey a string con formato optimizado

type CacheMetrics

type CacheMetrics struct {
	Hits     int64
	Misses   int64
	Sets     int64
	Deletes  int64
	Errors   int64
	HitRatio float64

	// Métricas avanzadas
	LatencySum       int64 // Microsegundos
	OperationCount   int64
	EvictionCount    int64
	CompressionRatio float64
	NetworkErrors    int64
	TimeoutErrors    int64

	// Métricas de negocio específicas
	UserCacheHits    int64
	SessionCacheHits int64
	QueryCacheHits   int64
	BusinessMetrics  map[string]int64
	// contains filtered or unexported fields
}

CacheMetrics rastrea estadísticas avanzadas de cache con métricas de negocio

type CacheService added in v1.0.0

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

CacheService provides high-level caching operations

func NewCacheService added in v1.0.0

func NewCacheService(client *RedisClient, logger logger.Logger) *CacheService

NewCacheService creates a new cache service

func (*CacheService) GetOrSet added in v1.0.0

func (cs *CacheService) GetOrSet(ctx context.Context, key string, dest interface{}, setter func() (interface{}, error), ttl time.Duration) error

GetOrSet gets a value from cache, or sets it if not found

type CacheWrapper added in v1.0.2

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

CacheWrapper proporciona funcionalidades de alto nivel para operaciones de cache comunes

func NewCacheWrapper added in v1.0.2

func NewCacheWrapper(manager *RedisManager, namespace string) *CacheWrapper

NewCacheWrapper crea un wrapper de cache con funcionalidades avanzadas

func (*CacheWrapper) GetMetrics added in v1.0.2

func (cw *CacheWrapper) GetMetrics() map[string]interface{}

GetMetrics retorna métricas del wrapper

func (*CacheWrapper) GetMultiple added in v1.0.2

func (cw *CacheWrapper) GetMultiple(ctx context.Context, keys []CacheKey) (map[string]interface{}, error)

GetMultiple obtiene múltiples claves de cache de forma eficiente

func (*CacheWrapper) GetOrSet added in v1.0.2

func (cw *CacheWrapper) GetOrSet(ctx context.Context, key CacheKey, dataType string,
	loadFunc func() (interface{}, error)) (interface{}, error)

GetOrSet implementa patrón cache-aside con función de carga

func (*CacheWrapper) GetOrSetJSON added in v1.0.2

func (cw *CacheWrapper) GetOrSetJSON(ctx context.Context, key CacheKey, dataType string,
	target interface{}, loadFunc func() error) error

GetOrSetJSON implementa GetOrSet específicamente para objetos JSON

func (*CacheWrapper) InvalidatePattern added in v1.0.2

func (cw *CacheWrapper) InvalidatePattern(ctx context.Context, pattern CacheKey) error

InvalidatePattern invalida múltiples claves basadas en patrón

func (*CacheWrapper) Lock added in v1.0.2

func (cw *CacheWrapper) Lock(ctx context.Context, lockKey string, ttl time.Duration) (*DistributedLock, error)

Lock implementa locks distribuidos usando Redis

func (*CacheWrapper) RefreshCache added in v1.0.2

func (cw *CacheWrapper) RefreshCache(ctx context.Context, key CacheKey, dataType string,
	loadFunc func() (interface{}, error)) error

RefreshCache actualiza datos en cache de forma proactiva

func (*CacheWrapper) SetMultiple added in v1.0.2

func (cw *CacheWrapper) SetMultiple(ctx context.Context, entries map[CacheKey]MultipleEntry) error

SetMultiple almacena múltiples claves de cache de forma eficiente

func (*CacheWrapper) WarmCache added in v1.0.2

func (cw *CacheWrapper) WarmCache(ctx context.Context, warmupData map[CacheKey]WarmupEntry) error

WarmCache precarga datos críticos en el cache

type CircuitBreaker added in v1.0.2

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

CircuitBreaker implementa patrón circuit breaker para Redis

type Config added in v1.0.2

type Config struct {
	// Configuración básica
	Host      string
	Port      string
	Password  string
	DB        int
	Namespace string
	TTL       time.Duration
	Mode      string

	// Pool de conexiones optimizado
	PoolSize     int
	MinIdleConns int
	MaxRetries   int
	MaxConnAge   time.Duration

	// Timeouts configurables
	DialTimeout  time.Duration
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	PoolTimeout  time.Duration

	// Configuración de cluster (si aplica)
	ClusterAddrs []string

	// Características avanzadas
	EnableCompression    bool
	EnableEncryption     bool
	EncryptionKey        string
	EnableCircuitBreaker bool
	EnableRetryPolicy    bool

	// Configuración de salud
	HealthCheckInterval time.Duration
	MaxFailureThreshold int

	// Configuración de métricas
	EnablePrometheusMetrics bool
	MetricsNamespace        string

	// Integración con gopherkit
	BaseConfig   *config.BaseConfig
	AlertManager *monitoring.AlertManager
}

Config mantiene configuración avanzada de Redis

func LoadConfigFromBase added in v1.0.2

func LoadConfigFromBase(baseConfig *config.BaseConfig, serviceName string) *Config

LoadConfigFromBase carga configuración Redis desde BaseConfig de gopherkit

type DistributedLock added in v1.0.2

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

DistributedLock implementa un lock distribuido usando Redis

func NewDistributedLock added in v1.0.2

func NewDistributedLock(manager *RedisManager, key string, ttl time.Duration) (*DistributedLock, error)

NewDistributedLock crea un nuevo lock distribuido

func (*DistributedLock) Acquire added in v1.0.2

func (dl *DistributedLock) Acquire(ctx context.Context) error

Acquire intenta adquirir el lock

func (*DistributedLock) Release added in v1.0.2

func (dl *DistributedLock) Release(ctx context.Context) error

Release libera el lock

type MemoryCache

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

MemoryCache implementa un cache en memoria con TTL

func NewMemoryCache

func NewMemoryCache(maxSize int) *MemoryCache

NewMemoryCache crea un nuevo cache de memoria

func (*MemoryCache) Clear

func (c *MemoryCache) Clear()

Clear limpia todo el cache

func (*MemoryCache) Close

func (c *MemoryCache) Close()

Close detiene el cache de memoria

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(key string)

Delete elimina una clave del cache de memoria

func (*MemoryCache) Exists

func (c *MemoryCache) Exists(key string) bool

Exists verifica si una clave existe en el cache de memoria

func (*MemoryCache) Get

func (c *MemoryCache) Get(key string, dest interface{}) error

Get obtiene un valor del cache de memoria

func (*MemoryCache) GetStats

func (c *MemoryCache) GetStats() map[string]interface{}

GetStats retorna estadísticas del cache

func (*MemoryCache) GetTTL

func (c *MemoryCache) GetTTL(key string) time.Duration

GetTTL obtiene el tiempo de vida restante de una clave

func (*MemoryCache) Increment

func (c *MemoryCache) Increment(key string, delta int64) int64

Increment atomically increments a numeric value

func (*MemoryCache) InvalidatePattern

func (c *MemoryCache) InvalidatePattern(pattern string)

InvalidatePattern elimina todas las claves que coinciden con un patrón

func (*MemoryCache) Set

func (c *MemoryCache) Set(key string, value interface{}, expiration time.Duration) error

Set guarda un valor en el cache de memoria

func (*MemoryCache) SetNX

func (c *MemoryCache) SetNX(key string, value interface{}, expiration time.Duration) bool

SetNX sets a key only if it doesn't exist

type MemoryCacheItem

type MemoryCacheItem struct {
	Value      interface{}
	Expiration time.Time
	CreatedAt  time.Time
}

MemoryCacheItem representa un elemento en el cache de memoria

func (*MemoryCacheItem) IsExpired

func (item *MemoryCacheItem) IsExpired() bool

IsExpired verifica si el elemento ha expirado

type MemoryCacheStats

type MemoryCacheStats struct {
	Hits      int64
	Misses    int64
	Sets      int64
	Deletes   int64
	Evictions int64
	Size      int64
	// contains filtered or unexported fields
}

MemoryCacheStats estadísticas del cache de memoria

type MultipleEntry added in v1.0.2

type MultipleEntry struct {
	Data     interface{}
	DataType string
}

MultipleEntry define una entrada para operaciones múltiples

type OperationMetrics

type OperationMetrics struct {
	Count     int64
	TotalTime time.Duration
	LastTime  time.Time
	Errors    int64
}

OperationMetrics métricas para una operación específica

type PerformanceStats added in v1.0.2

type PerformanceStats struct {
	TotalOperations     int64
	AverageLatency      float64
	P95Latency          float64
	P99Latency          float64
	ThroughputPerSecond float64
	LastUpdated         time.Time
	// contains filtered or unexported fields
}

PerformanceStats mantiene estadísticas de rendimiento

type RedisClient added in v1.0.0

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

RedisClient provides Redis caching operations

func NewRedisClient added in v1.0.0

func NewRedisClient(opts RedisOptions) (*RedisClient, error)

NewRedisClient creates a new Redis client

func (*RedisClient) Close added in v1.0.0

func (rc *RedisClient) Close() error

Close closes the Redis connection

func (*RedisClient) Delete added in v1.0.0

func (rc *RedisClient) Delete(ctx context.Context, key string) error

Delete removes a key from cache

func (*RedisClient) Exists added in v1.0.0

func (rc *RedisClient) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists

func (*RedisClient) Expire added in v1.0.0

func (rc *RedisClient) Expire(ctx context.Context, key string, ttl time.Duration) error

Expire sets TTL for a key

func (*RedisClient) FlushPattern added in v1.0.0

func (rc *RedisClient) FlushPattern(ctx context.Context, pattern string) error

FlushPattern deletes all keys matching a pattern

func (*RedisClient) Get added in v1.0.0

func (rc *RedisClient) Get(ctx context.Context, key string, dest interface{}) error

Get retrieves a value by key

func (*RedisClient) GetClient added in v1.0.0

func (rc *RedisClient) GetClient() redis.UniversalClient

GetClient returns the underlying Redis client for advanced operations

func (*RedisClient) GetMultiple added in v1.0.0

func (rc *RedisClient) GetMultiple(ctx context.Context, keys []string) (map[string]interface{}, error)

GetMultiple gets multiple keys at once

func (*RedisClient) GetTTL added in v1.0.0

func (rc *RedisClient) GetTTL(ctx context.Context, key string) (time.Duration, error)

GetTTL gets the remaining TTL for a key

func (*RedisClient) HealthCheck added in v1.0.0

func (rc *RedisClient) HealthCheck() observability.HealthCheck

HealthCheck returns a health check for Redis

func (*RedisClient) Increment added in v1.0.0

func (rc *RedisClient) Increment(ctx context.Context, key string) (int64, error)

Increment atomically increments a key

func (*RedisClient) IncrementBy added in v1.0.0

func (rc *RedisClient) IncrementBy(ctx context.Context, key string, value int64) (int64, error)

IncrementBy atomically increments a key by a given amount

func (*RedisClient) Ping added in v1.0.0

func (rc *RedisClient) Ping(ctx context.Context) error

Ping tests Redis connection

func (*RedisClient) Set added in v1.0.0

func (rc *RedisClient) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set stores a value with key

func (*RedisClient) SetNX added in v1.0.0

func (rc *RedisClient) SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)

SetNX sets a key only if it doesn't exist (atomic operation)

type RedisManager added in v1.0.2

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

RedisManager gestiona conexiones Redis con soporte avanzado para namespace, métricas y configuración dinámica

func GetInstance added in v1.0.2

func GetInstance(config *Config) (*RedisManager, error)

GetInstance retorna instancia singleton de RedisManager con configuración thread-safe

func NewRedisManager added in v1.0.2

func NewRedisManager(config *Config) (*RedisManager, error)

NewRedisManager crea un nuevo gestor Redis con configuración mejorada

func (*RedisManager) Close added in v1.0.2

func (rm *RedisManager) Close() error

Close cierra la conexión Redis de forma graciosa

func (*RedisManager) Delete added in v1.0.2

func (rm *RedisManager) Delete(ctx context.Context, keys ...string) error

Delete elimina una o más claves del cache

func (*RedisManager) DeletePattern added in v1.0.2

func (rm *RedisManager) DeletePattern(ctx context.Context, pattern string) error

DeletePattern elimina todas las claves que coinciden con un patrón

func (*RedisManager) Get added in v1.0.2

func (rm *RedisManager) Get(ctx context.Context, key string) (string, error)

Get recupera un valor de cache con circuit breaker y métricas

func (*RedisManager) GetJSON added in v1.0.2

func (rm *RedisManager) GetJSON(ctx context.Context, key string, dest interface{}) error

GetJSON recupera y deserializa un valor JSON del cache

func (*RedisManager) GetMetrics added in v1.0.2

func (rm *RedisManager) GetMetrics() map[string]interface{}

GetMetrics retorna métricas completas del cache

func (*RedisManager) Health added in v1.0.2

func (rm *RedisManager) Health(ctx context.Context) error

Health verifica la salud de la conexión Redis

func (*RedisManager) Set added in v1.0.2

func (rm *RedisManager) Set(ctx context.Context, key string, value interface{}) error

Set almacena un valor en cache con TTL por defecto y características avanzadas

func (*RedisManager) SetNX added in v1.0.2

func (rm *RedisManager) SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)

SetNX almacena un valor solo si la clave no existe (operación atómica)

func (*RedisManager) SetWithTTL added in v1.0.2

func (rm *RedisManager) SetWithTTL(ctx context.Context, key string, value interface{}, ttl time.Duration) error

SetWithTTL almacena un valor en cache con TTL personalizado

type RedisOptions added in v1.0.0

type RedisOptions struct {
	Config config.CacheConfig
	Logger logger.Logger
}

RedisOptions holds options for Redis client

type RetryPolicy added in v1.0.2

type RetryPolicy struct {
	MaxAttempts    int
	InitialDelay   time.Duration
	MaxDelay       time.Duration
	BackoffFactor  float64
	RetryCondition func(error) bool
}

RetryPolicy define política de reintentos

type TTLCalculator added in v1.0.2

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

TTLCalculator calcula TTLs dinámicos basados en contexto

func NewTTLCalculator added in v1.0.2

func NewTTLCalculator(baseTTL time.Duration) *TTLCalculator

NewTTLCalculator crea un calculador de TTL con estrategias predefinidas

func (*TTLCalculator) CalculateTTL added in v1.0.2

func (tc *TTLCalculator) CalculateTTL(dataType string, accessCount int64) time.Duration

CalculateTTL calcula TTL dinámico para un tipo de dato específico

type TTLStrategy added in v1.0.2

type TTLStrategy struct {
	MinTTL      time.Duration
	MaxTTL      time.Duration
	Multiplier  float64
	Randomness  float64 // Factor de aleatoridad para evitar cache stampede
	AccessBased bool    // TTL basado en frecuencia de acceso
}

TTLStrategy define estrategia de TTL para diferentes tipos de datos

type UnifiedCache

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

UnifiedCache implementación unificada de cache con Redis y fallback en memoria

func NewUnifiedCache

func NewUnifiedCache(config *CacheConfig, logger *logrus.Logger) (*UnifiedCache, error)

NewUnifiedCache crea una nueva instancia de cache unificado

func (*UnifiedCache) Close

func (c *UnifiedCache) Close() error

Close cierra todas las conexiones del cache

func (*UnifiedCache) Delete

func (c *UnifiedCache) Delete(ctx context.Context, key string) error

Delete elimina una clave del cache

func (*UnifiedCache) Exists

func (c *UnifiedCache) Exists(ctx context.Context, key string) bool

Exists verifica si una clave existe en el cache

func (*UnifiedCache) Get

func (c *UnifiedCache) Get(ctx context.Context, key string, dest interface{}) error

Get obtiene un valor del cache

func (*UnifiedCache) GetMultiple

func (c *UnifiedCache) GetMultiple(ctx context.Context, keys []string) (map[string]interface{}, error)

GetMultiple obtiene múltiples valores del cache

func (*UnifiedCache) GetStats

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

GetStats obtiene estadísticas del cache

func (*UnifiedCache) GetTTL

func (c *UnifiedCache) GetTTL(ctx context.Context, key string) time.Duration

GetTTL obtiene el tiempo de vida restante de una clave

func (*UnifiedCache) Increment

func (c *UnifiedCache) Increment(ctx context.Context, key string, delta int64) (int64, error)

Increment atomically increments a numeric value

func (*UnifiedCache) InvalidatePattern

func (c *UnifiedCache) InvalidatePattern(ctx context.Context, pattern string) error

InvalidatePattern elimina todas las claves que coinciden con un patrón

func (*UnifiedCache) Ping

func (c *UnifiedCache) Ping(ctx context.Context) error

Ping verifica la conectividad del cache

func (*UnifiedCache) Set

func (c *UnifiedCache) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error

Set guarda un valor en el cache

func (*UnifiedCache) SetMultiple

func (c *UnifiedCache) SetMultiple(ctx context.Context, items map[string]interface{}, expiration time.Duration) error

SetMultiple guarda múltiples valores en el cache

func (*UnifiedCache) SetNX

func (c *UnifiedCache) SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) (bool, error)

SetNX sets a key only if it doesn't exist

type WarmupEntry added in v1.0.2

type WarmupEntry struct {
	DataType string
	LoadFunc func() (interface{}, error)
}

WarmupEntry define una entrada para precarga de cache

type WrapperMetrics added in v1.0.2

type WrapperMetrics struct {
	FallbackHits          int64
	SerializationErrors   int64
	DeserializationErrors int64
	CompressionSavings    int64
	// contains filtered or unexported fields
}

WrapperMetrics mantiene métricas específicas del wrapper

Jump to

Keyboard shortcuts

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