Documentation
¶
Overview ¶
Package cache provides JSON-aware helper functions built on top of the Cache interface. These helpers automatically serialize/deserialize values using encoding/json, allowing any JSON-serializable type to be stored without manual marshaling.
Package cache provides a multi-level caching system and distributed lock implementation.
It defines a unified Cache interface that can be implemented by both local memory engines (like Ristretto) and remote distributed engines (like Redis). It also provides a DistributedLock interface for concurrency control across nodes.
Basic usage:
localCache, _ := cache.NewMemoryCache(100 * 1024 * 1024) // 100MB localCache.Set(ctx, "key", "value", 5*time.Minute) val, err := localCache.Get(ctx, "key")
Index ¶
- Variables
- func GetJSON[T any](ctx context.Context, c Cache, key string, dest *T) error
- func GetOrSetJSON[T any](ctx context.Context, c Cache, key string, ttl time.Duration, ...) (T, error)
- func SetJSON[T any](ctx context.Context, c Cache, key string, value T, ttl time.Duration) error
- type Cache
- type DistributedLock
- type MemoryCache
- func (m *MemoryCache) Clear(ctx context.Context) error
- func (m *MemoryCache) Close() error
- func (m *MemoryCache) Delete(ctx context.Context, key string) error
- func (m *MemoryCache) Get(ctx context.Context, key string) (string, error)
- func (m *MemoryCache) Set(ctx context.Context, key string, value string, ttl time.Duration) error
- type RedisCache
- func (r *RedisCache) Clear(ctx context.Context) error
- func (r *RedisCache) Close() error
- func (r *RedisCache) Delete(ctx context.Context, key string) error
- func (r *RedisCache) Get(ctx context.Context, key string) (string, error)
- func (r *RedisCache) Set(ctx context.Context, key string, value string, ttl time.Duration) error
- type RedisLock
- func (l *RedisLock) Acquire(ctx context.Context, key string, ttl time.Duration) (bool, error)
- func (l *RedisLock) Extend(ctx context.Context, key string, ttl time.Duration) (bool, error)
- func (l *RedisLock) NewSession() (*RedisLock, error)
- func (l *RedisLock) Release(ctx context.Context, key string) error
Constants ¶
This section is empty.
Variables ¶
var ( // ErrLockAcquisitionFailed is returned when the lock is already held by another client. ErrLockAcquisitionFailed = errors.New("cache: failed to acquire distributed lock") )
var ( // ErrNotFound is returned when a requested key does not exist in the cache. ErrNotFound = errors.New("cache: key not found") )
Functions ¶
func GetJSON ¶ added in v0.15.0
GetJSON retrieves a value from the cache and deserializes it from JSON into dest. dest must be a pointer. Returns ErrNotFound if the key does not exist.
Example:
var user UserProfile
err := cache.GetJSON(ctx, myCache, "user:123", &user)
if errors.Is(err, cache.ErrNotFound) { ... }
func GetOrSetJSON ¶ added in v0.15.0
func GetOrSetJSON[T any](ctx context.Context, c Cache, key string, ttl time.Duration, fetch func() (T, error)) (T, error)
GetOrSetJSON retrieves a value from cache; on miss, calls fetch() to compute the value, stores it, and returns it. Useful for the cache-aside pattern.
Example:
user, err := cache.GetOrSetJSON(ctx, myCache, "user:123", 5*time.Minute, func() (*User, error) {
return userRepo.FindByID(ctx, 123)
})
Types ¶
type Cache ¶
type Cache interface {
// Get retrieves a value from the cache. Returns an error (e.g., ErrNotFound) if not found.
Get(ctx context.Context, key string) (string, error)
// Set stores a value in the cache with an optional Time-To-Live (TTL).
// A TTL of 0 means the key does not expire.
Set(ctx context.Context, key string, value string, ttl time.Duration) error
// Delete removes a key from the cache.
Delete(ctx context.Context, key string) error
// Clear completely flushes the cache.
Clear(ctx context.Context) error
// Close releases resources held by the cache engine (e.g. background goroutines).
// It must be called when the cache is no longer needed.
Close() error
}
Cache defines the standard behavior for a caching engine (either local or remote).
type DistributedLock ¶
type DistributedLock interface {
// Acquire attempts to acquire the lock with a given TTL.
// Returns true if successfully acquired, false otherwise.
Acquire(ctx context.Context, key string, ttl time.Duration) (bool, error)
// Release releases the lock.
Release(ctx context.Context, key string) error
// Extend attempts to extend the TTL of a lock currently held by the caller.
Extend(ctx context.Context, key string, ttl time.Duration) (bool, error)
}
DistributedLock defines the behavior for a cluster-wide mutual exclusion lock.
type MemoryCache ¶
type MemoryCache struct {
// contains filtered or unexported fields
}
MemoryCache implements the Cache interface using dgraph-io/ristretto.
func NewMemoryCache ¶
func NewMemoryCache(maxCostBytes int64) (*MemoryCache, error)
NewMemoryCache creates a new in-memory cache with bounded max cost (in bytes). Note: It is highly concurrent and uses TinyLFU for optimal cache admission.
func (*MemoryCache) Clear ¶
func (m *MemoryCache) Clear(ctx context.Context) error
Clear completely flushes the cache.
func (*MemoryCache) Close ¶ added in v0.11.0
func (m *MemoryCache) Close() error
Close releases resources held by the Ristretto cache, stopping its background goroutines.
func (*MemoryCache) Delete ¶
func (m *MemoryCache) Delete(ctx context.Context, key string) error
Delete removes a key from the cache.
type RedisCache ¶
type RedisCache struct {
// contains filtered or unexported fields
}
RedisCache implements the Cache interface using Redis.
func NewRedisCache ¶
func NewRedisCache(client redis.UniversalClient) *RedisCache
NewRedisCache creates a new remote cache instance using a provided Redis client. This allows reusing the connection pool from the existing db/redis module.
func (*RedisCache) Clear ¶
func (r *RedisCache) Clear(ctx context.Context) error
Clear flushes the current Redis database. WARNING: Use with caution.
func (*RedisCache) Close ¶ added in v0.11.0
func (r *RedisCache) Close() error
Close is a no-op for RedisCache. The lifecycle of the underlying Redis client is managed externally (e.g. by the redis.Client wrapper); do not close it here.
func (*RedisCache) Delete ¶
func (r *RedisCache) Delete(ctx context.Context, key string) error
Delete removes a key from Redis.
type RedisLock ¶
type RedisLock struct {
// contains filtered or unexported fields
}
RedisLock implements DistributedLock using Redis SETNX with a random token to prevent accidental release.
func NewRedisLock ¶
func NewRedisLock(client redis.UniversalClient) *RedisLock
NewRedisLock creates a new DistributedLock instance.
func (*RedisLock) Acquire ¶
Acquire attempts to acquire a lock for a given key with a specified TTL.
func (*RedisLock) Extend ¶
Extend extends the TTL of a lock, ensuring the caller actually holds the lock via token check.
func (*RedisLock) NewSession ¶ added in v1.12.0
NewSession returns an independent ownership token backed by the same client. Use a new session for each execution so a stale owner cannot renew/release a later execution's lease, even when one RedisLock instance is shared.