Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrMemoryLimitExceeded is returned when the cache cannot accept additional entries due to size limits or unavailable eviction candidates. ErrMemoryLimitExceeded = errors.New("memory cache size limit exceeded") // ErrCacheClosed is returned when cache operations are attempted after Close has been called. ErrCacheClosed = errors.New("cache closed") // ErrLoaderRequired is returned when GetOrLoad is called without providing a loader. ErrLoaderRequired = errors.New("cache loader is required") // ErrTypeAssertionFailed is returned when singleflight type assertion fails. ErrTypeAssertionFailed = errors.New("singleflight: type assertion failed") )
Functions ¶
Types ¶
type Cache ¶
type Cache[T any] interface { io.Closer // Get retrieves a value by key. Returns the value and true if found, zero value and false if not found. Get(ctx context.Context, key string) (T, bool) // GetOrLoad retrieves a value by key or computes it using the provided loader when missing. // Implementations must ensure concurrent calls for the same key only trigger a single loader execution. GetOrLoad(ctx context.Context, key string, loader LoaderFunc[T], ttl ...time.Duration) (T, error) // Set stores a value with the given key. If ttl is provided and > 0, the entry will expire after the duration. Set(ctx context.Context, key string, value T, ttl ...time.Duration) error // Contains checks if a key exists in the cache. Contains(ctx context.Context, key string) bool // Delete removes a key from the cache. Delete(ctx context.Context, key string) error // Clear removes all entries from the cache. Clear(ctx context.Context) error // Keys returns all keys in the cache, optionally filtered by prefix. Keys(ctx context.Context, prefix ...string) ([]string, error) // ForEach iterates over all key-value pairs in the cache, optionally filtered by prefix. // The iteration stops if the callback returns false. ForEach(ctx context.Context, callback func(key string, value T) bool, prefix ...string) error // Size returns the number of entries in the cache. Size(ctx context.Context) (int64, error) }
Cache defines the interface for a generic key-value cache.
func NewMemory ¶
func NewMemory[T any](opts ...MemoryOption) Cache[T]
NewMemory constructs an in-memory cache using functional options.
type EvictionPolicy ¶
type EvictionPolicy int
EvictionPolicy defines the eviction strategy for cache when it reaches max size.
const ( // EvictionPolicyNone disables eviction tracking (used for unlimited caches). EvictionPolicyNone EvictionPolicy = iota // EvictionPolicyLRU evicts least recently used entries when cache is full. EvictionPolicyLRU // EvictionPolicyLFU evicts least frequently used entries when cache is full. EvictionPolicyLFU // EvictionPolicyFIFO evicts oldest entries when cache is full. EvictionPolicyFIFO )
type Invalidating ¶ added in v0.28.0
type Invalidating[T any] struct { // contains filtered or unexported fields }
Invalidating is a read-through cache whose entries are evicted out-of-band — typically when a domain event reports which keys changed. It owns an in-memory cache (which already coordinates concurrent loads to prevent stampede) and leaves the choice of invalidation trigger to the caller: wire a subscription that forwards the affected keys to Invalidate.
func NewInvalidating ¶ added in v0.28.0
func NewInvalidating[T any](loader KeyedLoaderFunc[T], logger logx.Logger) *Invalidating[T]
NewInvalidating builds an Invalidating cache that loads missing keys with loader and reports eviction activity through logger.
func (*Invalidating[T]) Get ¶ added in v0.28.0
func (i *Invalidating[T]) Get(ctx context.Context, key string) (T, error)
Get returns the value for key, loading and caching it on a miss.
func (*Invalidating[T]) Invalidate ¶ added in v0.28.0
func (i *Invalidating[T]) Invalidate(ctx context.Context, keys ...string) error
Invalidate evicts the named keys, or the entire cache when keys is empty.
type KeyBuilder ¶
type KeyBuilder interface {
// Build constructs a cache key from the given base key
Build(keyParts ...string) string
}
KeyBuilder defines the interface for building cache keys with different naming strategies.
type KeyedLoaderFunc ¶ added in v0.28.0
KeyedLoaderFunc loads the value for a single cache key. It is the per-key counterpart of LoaderFunc, used by Invalidating where the key is known up front.
type LoaderFunc ¶
LoaderFunc defines a function that loads a value for a given key when cache miss happens.
type MemoryOption ¶
type MemoryOption func(*memoryConfig)
MemoryOption configures the behavior of NewMemory caches.
func WithMemDefaultTTL ¶
func WithMemDefaultTTL(ttl time.Duration) MemoryOption
func WithMemEvictionPolicy ¶
func WithMemEvictionPolicy(policy EvictionPolicy) MemoryOption
WithMemEvictionPolicy selects the eviction strategy used when max size is enforced.
func WithMemGCInterval ¶
func WithMemGCInterval(interval time.Duration) MemoryOption
func WithMemMaxSize ¶
func WithMemMaxSize(size int64) MemoryOption
A value <= 0 disables size limits.
type PrefixKeyBuilder ¶
type PrefixKeyBuilder struct {
// contains filtered or unexported fields
}
PrefixKeyBuilder implements KeyBuilder with prefix-based naming strategy.
func NewPrefixKeyBuilder ¶
func NewPrefixKeyBuilder(prefix string) *PrefixKeyBuilder
NewPrefixKeyBuilder creates a new prefix-based key builder with default ":" separator.
func NewPrefixKeyBuilderWithSeparator ¶
func NewPrefixKeyBuilderWithSeparator(prefix, separator string) *PrefixKeyBuilder
NewPrefixKeyBuilderWithSeparator creates a new prefix-based key builder with custom separator.
func (*PrefixKeyBuilder) Build ¶
func (k *PrefixKeyBuilder) Build(keyParts ...string) string
Build constructs a cache key with prefix.
type RedisOption ¶
type RedisOption func(*redisConfig)
RedisOption configures Redis-backed cache instances.
func WithRdsDefaultTTL ¶
func WithRdsDefaultTTL(ttl time.Duration) RedisOption
type SingleflightMixin ¶
type SingleflightMixin[T any] struct { // contains filtered or unexported fields }
SingleflightMixin provides reusable singleflight-backed GetOrLoad logic that cache implementations can embed to prevent cache stampede.
Usage:
type MyCache[T any] struct {
// ... other fields ...
loadMixin SingleflightMixin[T]
}
func (c *MyCache[T]) GetOrLoad(ctx context.Context, key string, loader LoaderFunc[T], ttl ...time.Duration) (T, error) {
return c.loadMixin.GetOrLoad(ctx, key, loader, ttl, c.Get, c.Set)
}
func (*SingleflightMixin[T]) GetOrLoad ¶
func (m *SingleflightMixin[T]) GetOrLoad( ctx context.Context, cacheKey string, loader LoaderFunc[T], ttl []time.Duration, getFn GetFunc[T], setFn SetFunc[T], ) (value T, _ error)
GetOrLoad retrieves a value from cache or loads it using the provided loader, coordinating concurrent requests for the same cacheKey to prevent cache stampede.