cache

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2025 License: MIT Imports: 16 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")
	ErrCacheMiss     = fmt.Errorf("cache miss")
)

Cache errors

Functions

This section is empty.

Types

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 CacheMetrics

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

CacheMetrics recolecta métricas de cache

func NewCacheMetrics

func NewCacheMetrics() *CacheMetrics

NewCacheMetrics crea un nuevo recolector de métricas

func (*CacheMetrics) GetStats

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

GetStats retorna todas las estadísticas

func (*CacheMetrics) RecordError

func (m *CacheMetrics) RecordError(operation string)

RecordError registra un error en una operación

func (*CacheMetrics) RecordOperation

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

RecordOperation registra una operación de cache

func (*CacheMetrics) RecordOperationWithDuration

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

RecordOperationWithDuration registra una operación con duración

func (*CacheMetrics) Reset

func (m *CacheMetrics) Reset()

Reset resetea todas las métricas

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 Client added in v1.0.0

type Client interface {
	Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
	Get(ctx context.Context, key string) (string, error)
	GetJSON(ctx context.Context, key string, dest interface{}) error
	SetJSON(ctx context.Context, key string, value interface{}, expiration time.Duration) error
	Delete(ctx context.Context, keys ...string) error
	Exists(ctx context.Context, key string) (bool, error)
	Expire(ctx context.Context, key string, expiration time.Duration) error
	Keys(ctx context.Context, pattern string) ([]string, error)
	FlushDB(ctx context.Context) error
	Ping(ctx context.Context) error
	Close() error

	// Operaciones avanzadas
	Increment(ctx context.Context, key string) (int64, error)
	Decrement(ctx context.Context, key string) (int64, error)
	SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) (bool, error)
	GetSet(ctx context.Context, key string, value interface{}) (string, error)

	// Operaciones de lista
	LPush(ctx context.Context, key string, values ...interface{}) error
	RPush(ctx context.Context, key string, values ...interface{}) error
	LPop(ctx context.Context, key string) (string, error)
	RPop(ctx context.Context, key string) (string, error)
	LLen(ctx context.Context, key string) (int64, error)
	LRange(ctx context.Context, key string, start, stop int64) ([]string, error)

	// Operaciones de conjunto
	SAdd(ctx context.Context, key string, members ...interface{}) error
	SMembers(ctx context.Context, key string) ([]string, error)
	SIsMember(ctx context.Context, key string, member interface{}) (bool, error)
	SRem(ctx context.Context, key string, members ...interface{}) error

	// Hash operations
	HSet(ctx context.Context, key string, values ...interface{}) error
	HGet(ctx context.Context, key, field string) (string, error)
	HGetAll(ctx context.Context, key string) (map[string]string, error)
	HDel(ctx context.Context, key string, fields ...string) error
	HExists(ctx context.Context, key, field string) (bool, error)
}

Client interface para operaciones de cache

func NewRedisClient added in v1.0.0

func NewRedisClient(config *RedisConfig) (Client, error)

NewRedisClient crea un nuevo cliente Redis

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 OperationMetrics

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

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

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 RedisConfig added in v1.0.0

type RedisConfig struct {
	Host               string
	Port               int
	Password           string
	DB                 int
	PoolSize           int
	MinIdleConns       int
	MaxConnAge         time.Duration
	PoolTimeout        time.Duration
	IdleTimeout        time.Duration
	IdleCheckFrequency time.Duration

	// Clustering
	ClusterMode  bool
	ClusterAddrs []string

	// Security
	TLSEnabled    bool
	TLSSkipVerify bool

	// Retry configuration
	MaxRetries      int
	MinRetryBackoff time.Duration
	MaxRetryBackoff time.Duration

	// Monitoring
	EnableMetrics    bool
	SlowLogEnabled   bool
	SlowLogThreshold time.Duration
}

RedisConfig configuración para cliente Redis

func DefaultRedisConfig added in v1.0.0

func DefaultRedisConfig() *RedisConfig

DefaultRedisConfig retorna configuración por defecto

type RedisOptions added in v1.0.0

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

RedisOptions holds options for Redis client

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

Jump to

Keyboard shortcuts

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