Documentation
¶
Overview ¶
Package cache is a generic in-process cache with TTL, LRU max-size eviction, and singleflight load deduplication. It complements redis.Remember for hot data that should not cost a network round-trip per read.
Index ¶
- type Cache
- func (c *Cache[V]) Close()
- func (c *Cache[V]) Delete(key string)
- func (c *Cache[V]) Get(key string) (V, bool)
- func (c *Cache[V]) GetOrLoad(ctx context.Context, key string, loader func() (V, error)) (V, error)
- func (c *Cache[V]) Len() int
- func (c *Cache[V]) Set(key string, val V)
- func (c *Cache[V]) SetTTL(key string, val V, ttl time.Duration)
- type Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache[V any] struct { // contains filtered or unexported fields }
Cache is a generic in-process cache.
Example ¶
A typed in-memory cache with load-through. GetOrLoad runs the loader once on a miss (deduplicating concurrent callers) and serves the cached value after.
package main
import (
"context"
"fmt"
"github.com/rahmadafandi/fibr/v2/cache"
)
func main() {
type User struct{ Name string }
c := cache.New[User](cache.WithMaxSize(1000))
ctx := context.Background()
load := func() (User, error) {
fmt.Println("loading from db")
return User{Name: "ada"}, nil
}
u, _ := c.GetOrLoad(ctx, "user:1", load) // miss -> loads
fmt.Println(u.Name)
u, _ = c.GetOrLoad(ctx, "user:1", load) // hit -> no load
fmt.Println(u.Name)
}
Output: loading from db ada ada
func (*Cache[V]) Close ¶
func (c *Cache[V]) Close()
Close stops the janitor goroutine, if any. It is safe to call multiple times.
func (*Cache[V]) GetOrLoad ¶
GetOrLoad returns the cached value for key, or runs loader once (deduplicating concurrent callers), caches the result under the default TTL, and returns it. A loader error is returned and nothing is cached.
func (*Cache[V]) Len ¶
Len returns the number of entries (including any not yet swept that may be expired).
type Option ¶
type Option func(*config)
Option configures a Cache.
func WithDefaultTTL ¶
WithDefaultTTL sets the TTL applied by Set and GetOrLoad. Zero (default) means entries do not expire.
func WithJanitor ¶
WithJanitor runs a background goroutine that sweeps expired entries every interval. Without it, expiry is lazy (checked on Get). Call Close to stop it.
func WithMaxSize ¶
WithMaxSize bounds the number of entries; the least-recently-used is evicted when the limit is exceeded. Zero (default) is unbounded.