{"modulePath":"github.com/lukcba-developers/gopherkit","version":"v1.0.3","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package cache\n\n## Variables\n\n```go\nvar (\n\t// ErrCacheMiss indicates that a key was not found in the cache\n\tErrCacheMiss = errors.New(\"cache miss\")\n\n\t// ErrCacheConnectionFailed indicates that the cache connection failed\n\tErrCacheConnectionFailed = errors.New(\"cache connection failed\")\n\n\t// ErrInvalidCacheKey indicates that the provided cache key is invalid\n\tErrInvalidCacheKey = errors.New(\"invalid cache key\")\n\n\t// ErrCacheFull indicates that the cache is full and cannot accept more items\n\tErrCacheFull = errors.New(\"cache is full\")\n\n\t// ErrSerializationFailed indicates that serialization of the value failed\n\tErrSerializationFailed = errors.New(\"serialization failed\")\n\n\t// ErrDeserializationFailed indicates that deserialization of the value failed\n\tErrDeserializationFailed = errors.New(\"deserialization failed\")\n\n\t// ErrCacheTimeout indicates that a cache operation timed out\n\tErrCacheTimeout = errors.New(\"cache operation timeout\")\n)\n```\nCache errors\n\n```go\nvar (\n\tErrCacheDisabled = fmt.Errorf(\"cache is disabled\")\n)\n```\nCache errors\n\n## Types\n\n```go\ntype BasicCacheMetrics struct {\n\t// contains filtered or unexported fields\n}\n```\nBasicCacheMetrics recolecta métricas de cache\n\n```go\nfunc NewBasicCacheMetrics() *BasicCacheMetrics\n```\nNewBasicCacheMetrics crea un nuevo recolector de métricas\n\n```go\nfunc (m *BasicCacheMetrics) GetStats() map[string]interface{}\n```\nGetStats retorna todas las estadísticas\n\n```go\nfunc (m *BasicCacheMetrics) RecordError(operation string)\n```\nRecordError registra un error en una operación\n\n```go\nfunc (m *BasicCacheMetrics) RecordOperation(operation, key string)\n```\nRecordOperation registra una operación de cache\n\n```go\nfunc (m *BasicCacheMetrics) RecordOperationWithDuration(operation, key string, duration time.Duration)\n```\nRecordOperationWithDuration registra una operación con duración\n\n```go\nfunc (m *BasicCacheMetrics) Reset()\n```\nReset resetea todas las métricas\n\n```go\ntype CacheConfig struct {\n\t// Redis Configuration\n\tRedisHost     string\n\tRedisPort     string\n\tRedisPassword string\n\tRedisDB       int\n\n\t// Connection Pool\n\tPoolSize     int\n\tMinIdleConns int\n\tMaxConnAge   time.Duration\n\tPoolTimeout  time.Duration\n\tIdleTimeout  time.Duration\n\n\t// Timeouts\n\tReadTimeout  time.Duration\n\tWriteTimeout time.Duration\n\tDialTimeout  time.Duration\n\n\t// Cache Behavior\n\tDefaultExpiration time.Duration\n\tKeyPrefix         string\n\tEnableCompression bool\n\tEnableMetrics     bool\n\n\t// Fallback Settings\n\tEnableMemoryFallback bool\n\tMemoryCacheSize      int\n}\n```\nCacheConfig configuración unificada de cache\n\n```go\nfunc DefaultCacheConfig() *CacheConfig\n```\nDefaultCacheConfig retorna configuración por defecto\n\n```go\ntype CacheInterface interface {\n\t// Basic operations\n\tGet(ctx context.Context, key string, dest interface{}) error\n\tSet(ctx context.Context, key string, value interface{}, expiration time.Duration) error\n\tDelete(ctx context.Context, key string) error\n\tExists(ctx context.Context, key string) bool\n\n\t// Advanced operations\n\tGetMultiple(ctx context.Context, keys []string) (map[string]interface{}, error)\n\tSetMultiple(ctx context.Context, items map[string]interface{}, expiration time.Duration) error\n\tInvalidatePattern(ctx context.Context, pattern string) error\n\n\t// Atomic operations\n\tSetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) (bool, error)\n\tIncrement(ctx context.Context, key string, delta int64) (int64, error)\n\n\t// Info operations\n\tGetTTL(ctx context.Context, key string) time.Duration\n\tPing(ctx context.Context) error\n\tGetStats(ctx context.Context) (map[string]interface{}, error)\n}\n```\nCacheInterface define la interfaz unificada de cache\n\n```go\ntype CacheKey struct {\n\tPrefix  string\n\tService string\n\tEntity  string\n\tID      string\n\tVersion string\n\tTenant  string\n\tSuffix  string\n}\n```\nCacheKey construye claves de cache consistentes y optimizadas\n\n```go\nfunc ConfigCacheKey(service, configType string, tenant ...string) CacheKey\n```\nConfigCacheKey construye clave de cache para configuración\n\n```go\nfunc QueryCacheKey(service, queryType, hash string, tenant ...string) CacheKey\n```\nQueryCacheKey construye clave de cache para resultados de consulta\n\n```go\nfunc SessionCacheKey(sessionID string, tenant ...string) CacheKey\n```\nSessionCacheKey construye clave de cache para datos de sesión\n\n```go\nfunc UserCacheKey(userID, dataType string, tenant ...string) CacheKey\n```\nUserCacheKey construye clave de cache para datos de usuario\n\n```go\nfunc (ck CacheKey) Pattern() string\n```\nCachePattern genera patrones para búsqueda/eliminación masiva\n\n```go\nfunc (ck CacheKey) String() string\n```\nString convierte CacheKey a string con formato optimizado\n\n```go\ntype CacheMetrics struct {\n\tHits     int64\n\tMisses   int64\n\tSets     int64\n\tDeletes  int64\n\tErrors   int64\n\tHitRatio float64\n\n\t// Métricas avanzadas\n\tLatencySum       int64 // Microsegundos\n\tOperationCount   int64\n\tEvictionCount    int64\n\tCompressionRatio float64\n\tNetworkErrors    int64\n\tTimeoutErrors    int64\n\n\t// Métricas de negocio específicas\n\tUserCacheHits    int64\n\tSessionCacheHits int64\n\tQueryCacheHits   int64\n\tBusinessMetrics  map[string]int64\n\t// contains filtered or unexported fields\n}\n```\nCacheMetrics rastrea estadísticas avanzadas de cache con métricas de negocio\n\n```go\ntype CacheService struct {\n\t// contains filtered or unexported fields\n}\n```\nCacheService provides high-level caching operations\n\n```go\nfunc NewCacheService(client *RedisClient, logger logger.Logger) *CacheService\n```\nNewCacheService creates a new cache service\n\n```go\nfunc (cs *CacheService) GetOrSet(ctx context.Context, key string, dest interface{}, setter func() (interface{}, error), ttl time.Duration) error\n```\nGetOrSet gets a value from cache, or sets it if not found\n\n```go\ntype CacheWrapper struct {\n\t// contains filtered or unexported fields\n}\n```\nCacheWrapper proporciona funcionalidades de alto nivel para operaciones de cache comunes\n\n```go\nfunc NewCacheWrapper(manager *RedisManager, namespace string) *CacheWrapper\n```\nNewCacheWrapper crea un wrapper de cache con funcionalidades avanzadas\n\n```go\nfunc (cw *CacheWrapper) GetMetrics() map[string]interface{}\n```\nGetMetrics retorna métricas del wrapper\n\n```go\nfunc (cw *CacheWrapper) GetMultiple(ctx context.Context, keys []CacheKey) (map[string]interface{}, error)\n```\nGetMultiple obtiene múltiples claves de cache de forma eficiente\n\n```go\nfunc (cw *CacheWrapper) GetOrSet(ctx context.Context, key CacheKey, dataType string,\n\tloadFunc func() (interface{}, error)) (interface{}, error)\n```\nGetOrSet implementa patrón cache-aside con función de carga\n\n```go\nfunc (cw *CacheWrapper) GetOrSetJSON(ctx context.Context, key CacheKey, dataType string,\n\ttarget interface{}, loadFunc func() error) error\n```\nGetOrSetJSON implementa GetOrSet específicamente para objetos JSON\n\n```go\nfunc (cw *CacheWrapper) InvalidatePattern(ctx context.Context, pattern CacheKey) error\n```\nInvalidatePattern invalida múltiples claves basadas en patrón\n\n```go\nfunc (cw *CacheWrapper) Lock(ctx context.Context, lockKey string, ttl time.Duration) (*DistributedLock, error)\n```\nLock implementa locks distribuidos usando Redis\n\n```go\nfunc (cw *CacheWrapper) RefreshCache(ctx context.Context, key CacheKey, dataType string,\n\tloadFunc func() (interface{}, error)) error\n```\nRefreshCache actualiza datos en cache de forma proactiva\n\n```go\nfunc (cw *CacheWrapper) SetMultiple(ctx context.Context, entries map[CacheKey]MultipleEntry) error\n```\nSetMultiple almacena múltiples claves de cache de forma eficiente\n\n```go\nfunc (cw *CacheWrapper) WarmCache(ctx context.Context, warmupData map[CacheKey]WarmupEntry) error\n```\nWarmCache precarga datos críticos en el cache\n\n```go\ntype CircuitBreaker struct {\n\t// contains filtered or unexported fields\n}\n```\nCircuitBreaker implementa patrón circuit breaker para Redis\n\n```go\ntype Config struct {\n\t// Configuración básica\n\tHost      string\n\tPort      string\n\tPassword  string\n\tDB        int\n\tNamespace string\n\tTTL       time.Duration\n\tMode      string\n\n\t// Pool de conexiones optimizado\n\tPoolSize     int\n\tMinIdleConns int\n\tMaxRetries   int\n\tMaxConnAge   time.Duration\n\n\t// Timeouts configurables\n\tDialTimeout  time.Duration\n\tReadTimeout  time.Duration\n\tWriteTimeout time.Duration\n\tPoolTimeout  time.Duration\n\n\t// Configuración de cluster (si aplica)\n\tClusterAddrs []string\n\n\t// Características avanzadas\n\tEnableCompression    bool\n\tEnableEncryption     bool\n\tEncryptionKey        string\n\tEnableCircuitBreaker bool\n\tEnableRetryPolicy    bool\n\n\t// Configuración de salud\n\tHealthCheckInterval time.Duration\n\tMaxFailureThreshold int\n\n\t// Configuración de métricas\n\tEnablePrometheusMetrics bool\n\tMetricsNamespace        string\n\n\t// Integración con gopherkit\n\tBaseConfig   *config.BaseConfig\n\tAlertManager *monitoring.AlertManager\n}\n```\nConfig mantiene configuración avanzada de Redis\n\n```go\nfunc LoadConfigFromBase(baseConfig *config.BaseConfig, serviceName string) *Config\n```\nLoadConfigFromBase carga configuración Redis desde BaseConfig de gopherkit\n\n```go\ntype DistributedLock struct {\n\t// contains filtered or unexported fields\n}\n```\nDistributedLock implementa un lock distribuido usando Redis\n\n```go\nfunc NewDistributedLock(manager *RedisManager, key string, ttl time.Duration) (*DistributedLock, error)\n```\nNewDistributedLock crea un nuevo lock distribuido\n\n```go\nfunc (dl *DistributedLock) Acquire(ctx context.Context) error\n```\nAcquire intenta adquirir el lock\n\n```go\nfunc (dl *DistributedLock) Release(ctx context.Context) error\n```\nRelease libera el lock\n\n```go\ntype MemoryCache struct {\n\t// contains filtered or unexported fields\n}\n```\nMemoryCache implementa un cache en memoria con TTL\n\n```go\nfunc NewMemoryCache(maxSize int) *MemoryCache\n```\nNewMemoryCache crea un nuevo cache de memoria\n\n```go\nfunc (c *MemoryCache) Clear()\n```\nClear limpia todo el cache\n\n```go\nfunc (c *MemoryCache) Close()\n```\nClose detiene el cache de memoria\n\n```go\nfunc (c *MemoryCache) Delete(key string)\n```\nDelete elimina una clave del cache de memoria\n\n```go\nfunc (c *MemoryCache) Exists(key string) bool\n```\nExists verifica si una clave existe en el cache de memoria\n\n```go\nfunc (c *MemoryCache) Get(key string, dest interface{}) error\n```\nGet obtiene un valor del cache de memoria\n\n```go\nfunc (c *MemoryCache) GetStats() map[string]interface{}\n```\nGetStats retorna estadísticas del cache\n\n```go\nfunc (c *MemoryCache) GetTTL(key string) time.Duration\n```\nGetTTL obtiene el tiempo de vida restante de una clave\n\n```go\nfunc (c *MemoryCache) Increment(key string, delta int64) int64\n```\nIncrement atomically increments a numeric value\n\n```go\nfunc (c *MemoryCache) InvalidatePattern(pattern string)\n```\nInvalidatePattern elimina todas las claves que coinciden con un patrón\n\n```go\nfunc (c *MemoryCache) Set(key string, value interface{}, expiration time.Duration) error\n```\nSet guarda un valor en el cache de memoria\n\n```go\nfunc (c *MemoryCache) SetNX(key string, value interface{}, expiration time.Duration) bool\n```\nSetNX sets a key only if it doesn't exist\n\n```go\ntype MemoryCacheItem struct {\n\tValue      interface{}\n\tExpiration time.Time\n\tCreatedAt  time.Time\n}\n```\nMemoryCacheItem representa un elemento en el cache de memoria\n\n```go\nfunc (item *MemoryCacheItem) IsExpired() bool\n```\nIsExpired verifica si el elemento ha expirado\n\n```go\ntype MemoryCacheStats struct {\n\tHits      int64\n\tMisses    int64\n\tSets      int64\n\tDeletes   int64\n\tEvictions int64\n\tSize      int64\n\t// contains filtered or unexported fields\n}\n```\nMemoryCacheStats estadísticas del cache de memoria\n\n```go\ntype MultipleEntry struct {\n\tData     interface{}\n\tDataType string\n}\n```\nMultipleEntry define una entrada para operaciones múltiples\n\n```go\ntype OperationMetrics struct {\n\tCount     int64\n\tTotalTime time.Duration\n\tLastTime  time.Time\n\tErrors    int64\n}\n```\nOperationMetrics métricas para una operación específica\n\n```go\ntype PerformanceStats struct {\n\tTotalOperations     int64\n\tAverageLatency      float64\n\tP95Latency          float64\n\tP99Latency          float64\n\tThroughputPerSecond float64\n\tLastUpdated         time.Time\n\t// contains filtered or unexported fields\n}\n```\nPerformanceStats mantiene estadísticas de rendimiento\n\n```go\ntype RedisClient struct {\n\t// contains filtered or unexported fields\n}\n```\nRedisClient provides Redis caching operations\n\n```go\nfunc NewRedisClient(opts RedisOptions) (*RedisClient, error)\n```\nNewRedisClient creates a new Redis client\n\n```go\nfunc (rc *RedisClient) Close() error\n```\nClose closes the Redis connection\n\n```go\nfunc (rc *RedisClient) Delete(ctx context.Context, key string) error\n```\nDelete removes a key from cache\n\n```go\nfunc (rc *RedisClient) Exists(ctx context.Context, key string) (bool, error)\n```\nExists checks if a key exists\n\n```go\nfunc (rc *RedisClient) Expire(ctx context.Context, key string, ttl time.Duration) error\n```\nExpire sets TTL for a key\n\n```go\nfunc (rc *RedisClient) FlushPattern(ctx context.Context, pattern string) error\n```\nFlushPattern deletes all keys matching a pattern\n\n```go\nfunc (rc *RedisClient) Get(ctx context.Context, key string, dest interface{}) error\n```\nGet retrieves a value by key\n\n```go\nfunc (rc *RedisClient) GetClient() redis.UniversalClient\n```\nGetClient returns the underlying Redis client for advanced operations\n\n```go\nfunc (rc *RedisClient) GetMultiple(ctx context.Context, keys []string) (map[string]interface{}, error)\n```\nGetMultiple gets multiple keys at once\n\n```go\nfunc (rc *RedisClient) GetTTL(ctx context.Context, key string) (time.Duration, error)\n```\nGetTTL gets the remaining TTL for a key\n\n```go\nfunc (rc *RedisClient) HealthCheck() observability.HealthCheck\n```\nHealthCheck returns a health check for Redis\n\n```go\nfunc (rc *RedisClient) Increment(ctx context.Context, key string) (int64, error)\n```\nIncrement atomically increments a key\n\n```go\nfunc (rc *RedisClient) IncrementBy(ctx context.Context, key string, value int64) (int64, error)\n```\nIncrementBy atomically increments a key by a given amount\n\n```go\nfunc (rc *RedisClient) Ping(ctx context.Context) error\n```\nPing tests Redis connection\n\n```go\nfunc (rc *RedisClient) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error\n```\nSet stores a value with key\n\n```go\nfunc (rc *RedisClient) SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)\n```\nSetNX sets a key only if it doesn't exist (atomic operation)\n\n```go\ntype RedisManager struct {\n\t// contains filtered or unexported fields\n}\n```\nRedisManager gestiona conexiones Redis con soporte avanzado para namespace, métricas y configuración dinámica\n\n```go\nfunc GetInstance(config *Config) (*RedisManager, error)\n```\nGetInstance retorna instancia singleton de RedisManager con configuración thread-safe\n\n```go\nfunc NewRedisManager(config *Config) (*RedisManager, error)\n```\nNewRedisManager crea un nuevo gestor Redis con configuración mejorada\n\n```go\nfunc (rm *RedisManager) Close() error\n```\nClose cierra la conexión Redis de forma graciosa\n\n```go\nfunc (rm *RedisManager) Delete(ctx context.Context, keys ...string) error\n```\nDelete elimina una o más claves del cache\n\n```go\nfunc (rm *RedisManager) DeletePattern(ctx context.Context, pattern string) error\n```\nDeletePattern elimina todas las claves que coinciden con un patrón\n\n```go\nfunc (rm *RedisManager) Get(ctx context.Context, key string) (string, error)\n```\nGet recupera un valor de cache con circuit breaker y métricas\n\n```go\nfunc (rm *RedisManager) GetJSON(ctx context.Context, key string, dest interface{}) error\n```\nGetJSON recupera y deserializa un valor JSON del cache\n\n```go\nfunc (rm *RedisManager) GetMetrics() map[string]interface{}\n```\nGetMetrics retorna métricas completas del cache\n\n```go\nfunc (rm *RedisManager) Health(ctx context.Context) error\n```\nHealth verifica la salud de la conexión Redis\n\n```go\nfunc (rm *RedisManager) Set(ctx context.Context, key string, value interface{}) error\n```\nSet almacena un valor en cache con TTL por defecto y características avanzadas\n\n```go\nfunc (rm *RedisManager) SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)\n```\nSetNX almacena un valor solo si la clave no existe (operación atómica)\n\n```go\nfunc (rm *RedisManager) SetWithTTL(ctx context.Context, key string, value interface{}, ttl time.Duration) error\n```\nSetWithTTL almacena un valor en cache con TTL personalizado\n\n```go\ntype RedisOptions struct {\n\tConfig config.CacheConfig\n\tLogger logger.Logger\n}\n```\nRedisOptions holds options for Redis client\n\n```go\ntype RetryPolicy struct {\n\tMaxAttempts    int\n\tInitialDelay   time.Duration\n\tMaxDelay       time.Duration\n\tBackoffFactor  float64\n\tRetryCondition func(error) bool\n}\n```\nRetryPolicy define política de reintentos\n\n```go\ntype TTLCalculator struct {\n\t// contains filtered or unexported fields\n}\n```\nTTLCalculator calcula TTLs dinámicos basados en contexto\n\n```go\nfunc NewTTLCalculator(baseTTL time.Duration) *TTLCalculator\n```\nNewTTLCalculator crea un calculador de TTL con estrategias predefinidas\n\n```go\nfunc (tc *TTLCalculator) CalculateTTL(dataType string, accessCount int64) time.Duration\n```\nCalculateTTL calcula TTL dinámico para un tipo de dato específico\n\n```go\ntype TTLStrategy struct {\n\tMinTTL      time.Duration\n\tMaxTTL      time.Duration\n\tMultiplier  float64\n\tRandomness  float64 // Factor de aleatoridad para evitar cache stampede\n\tAccessBased bool    // TTL basado en frecuencia de acceso\n}\n```\nTTLStrategy define estrategia de TTL para diferentes tipos de datos\n\n```go\ntype UnifiedCache struct {\n\t// contains filtered or unexported fields\n}\n```\nUnifiedCache implementación unificada de cache con Redis y fallback en memoria\n\n```go\nfunc NewUnifiedCache(config *CacheConfig, logger *logrus.Logger) (*UnifiedCache, error)\n```\nNewUnifiedCache crea una nueva instancia de cache unificado\n\n```go\nfunc (c *UnifiedCache) Close() error\n```\nClose cierra todas las conexiones del cache\n\n```go\nfunc (c *UnifiedCache) Delete(ctx context.Context, key string) error\n```\nDelete elimina una clave del cache\n\n```go\nfunc (c *UnifiedCache) Exists(ctx context.Context, key string) bool\n```\nExists verifica si una clave existe en el cache\n\n```go\nfunc (c *UnifiedCache) Get(ctx context.Context, key string, dest interface{}) error\n```\nGet obtiene un valor del cache\n\n```go\nfunc (c *UnifiedCache) GetMultiple(ctx context.Context, keys []string) (map[string]interface{}, error)\n```\nGetMultiple obtiene múltiples valores del cache\n\n```go\nfunc (c *UnifiedCache) GetStats(ctx context.Context) (map[string]interface{}, error)\n```\nGetStats obtiene estadísticas del cache\n\n```go\nfunc (c *UnifiedCache) GetTTL(ctx context.Context, key string) time.Duration\n```\nGetTTL obtiene el tiempo de vida restante de una clave\n\n```go\nfunc (c *UnifiedCache) Increment(ctx context.Context, key string, delta int64) (int64, error)\n```\nIncrement atomically increments a numeric value\n\n```go\nfunc (c *UnifiedCache) InvalidatePattern(ctx context.Context, pattern string) error\n```\nInvalidatePattern elimina todas las claves que coinciden con un patrón\n\n```go\nfunc (c *UnifiedCache) Ping(ctx context.Context) error\n```\nPing verifica la conectividad del cache\n\n```go\nfunc (c *UnifiedCache) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error\n```\nSet guarda un valor en el cache\n\n```go\nfunc (c *UnifiedCache) SetMultiple(ctx context.Context, items map[string]interface{}, expiration time.Duration) error\n```\nSetMultiple guarda múltiples valores en el cache\n\n```go\nfunc (c *UnifiedCache) SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) (bool, error)\n```\nSetNX sets a key only if it doesn't exist\n\n```go\ntype WarmupEntry struct {\n\tDataType string\n\tLoadFunc func() (interface{}, error)\n}\n```\nWarmupEntry define una entrada para precarga de cache\n\n```go\ntype WrapperMetrics struct {\n\tFallbackHits          int64\n\tSerializationErrors   int64\n\tDeserializationErrors int64\n\tCompressionSavings    int64\n\t// contains filtered or unexported fields\n}\n```\nWrapperMetrics mantiene métricas específicas del wrapper\n\n","path":"github.com/lukcba-developers/gopherkit/pkg/cache","name":"cache","synopsis":"","isRedistributable":true}
