Documentation
¶
Overview ¶
Package cache provides typed, composable caches.
A StandardCache applies a namespace and a default TTL to a Store, the storage contract implemented by the backend packages under backend/ (an in-process LRU, a bbolt file, Redis, Valkey, Dragonfly, Memcached, Hazelcast and PostgreSQL). Stores compose: LayeredStore stacks stores from fastest to slowest with read promotion and optional distributed invalidation through an InvalidationBus, and PullThroughCache loads misses with per-key single flight, negative caching and optional distributed fill leases from a Locker.
Entries are typed (Entry) and carry a logical expiration; a zero expiration, requested with NoExpiry, never expires. Persistent backends serialize keys and values with a Codec; DefaultCodec covers strings, byte slices, scalars and JSON-compatible values.
Cached data is assumed to be reconstructible and disposable. Fill leases reduce duplicate work but do not fence writes, and invalidation delivery is at-least-once without ordering guarantees.
All exported types are safe for concurrent use unless their documentation says otherwise. Operations that block or perform I/O take a context.Context and honour its cancellation.
Example ¶
package main
import (
"context"
"fmt"
"time"
cache "github.com/justusschock/cache"
"github.com/justusschock/cache/backend/memory"
)
type User struct {
ID string
Name string
}
func main() {
store := memory.New[string, User]()
defer func() { _ = store.Close() }()
users, err := cache.New("users", 5*time.Minute, store)
if err != nil {
panic(err)
}
ctx := context.Background()
if err := users.Set(ctx, "user-42", User{ID: "user-42", Name: "Ada"}); err != nil {
panic(err)
}
user, found, err := users.Get(ctx, "user-42")
if err != nil {
panic(err)
}
fmt.Println(found, user.Name)
}
Output: true Ada
Index ¶
- Constants
- Variables
- type BatchCache
- type BatchStore
- type Cache
- type Codec
- type CoordinationLocker
- type Entry
- type EntryCache
- type Event
- type FillKeyFunc
- type InvalidationBus
- type InvalidationEvent
- type InvalidationHandler
- type InvalidationKind
- type LayeredOption
- type LayeredStore
- func (s *LayeredStore[K, V]) Get(ctx context.Context, namespace string, key K) (Entry[V], bool, error)
- func (s *LayeredStore[K, V]) Invalidate(ctx context.Context, namespace string, key K) error
- func (s *LayeredStore[K, V]) InvalidateAll(ctx context.Context, namespace string) error
- func (s *LayeredStore[K, V]) ListenInvalidations(ctx context.Context, namespace string, lowerLayer int) error
- func (s *LayeredStore[K, V]) Set(ctx context.Context, namespace string, key K, entry Entry[V]) error
- type Lease
- type Loader
- type Locker
- type MessagingInvalidationBus
- type ObservableLease
- type Observer
- type PullThroughCache
- func (c *PullThroughCache[K, V]) Get(ctx context.Context, key K) (V, bool, error)
- func (c *PullThroughCache[K, V]) Invalidate(ctx context.Context, key K) error
- func (c *PullThroughCache[K, V]) InvalidateAll(ctx context.Context) error
- func (c *PullThroughCache[K, V]) Set(ctx context.Context, key K, value V) error
- func (c *PullThroughCache[K, V]) SetWithTTL(ctx context.Context, key K, value V, ttl time.Duration) error
- type PullThroughOption
- func WithLoadOnLockError[K comparable]() PullThroughOption[K]
- func WithLockPollInterval[K comparable](interval time.Duration) PullThroughOption[K]
- func WithLocker[K comparable](locker Locker[K], leaseTTL time.Duration) PullThroughOption[K]
- func WithNegativeTTL[K comparable](ttl time.Duration) PullThroughOption[K]
- func WithStrictPullThroughReads[K comparable]() PullThroughOption[K]
- type StandardCache
- func (c *StandardCache[K, V]) Get(ctx context.Context, key K) (V, bool, error)
- func (c *StandardCache[K, V]) GetEntry(ctx context.Context, key K) (Entry[V], bool, error)
- func (c *StandardCache[K, V]) GetMany(ctx context.Context, keys []K) ([]V, []bool, error)
- func (c *StandardCache[K, V]) Invalidate(ctx context.Context, key K) error
- func (c *StandardCache[K, V]) InvalidateAll(ctx context.Context) error
- func (c *StandardCache[K, V]) InvalidateMany(ctx context.Context, keys []K) error
- func (c *StandardCache[K, V]) Set(ctx context.Context, key K, value V) error
- func (c *StandardCache[K, V]) SetEntry(ctx context.Context, key K, entry Entry[V]) error
- func (c *StandardCache[K, V]) SetMany(ctx context.Context, keys []K, values []V) error
- func (c *StandardCache[K, V]) SetManyWithTTL(ctx context.Context, keys []K, values []V, ttl time.Duration) error
- func (c *StandardCache[K, V]) SetWithTTL(ctx context.Context, key K, value V, ttl time.Duration) error
- type Store
- type SubscriptionFactory
Examples ¶
Constants ¶
const NoExpiry time.Duration = math.MinInt64
NoExpiry is the explicit opt-in TTL for entries that never expire. New and SetWithTTL accept it in place of a positive duration; the resulting entries carry a zero ExpiresAt and remain until they are invalidated or evicted by the store. Every other non-positive TTL is still rejected with ErrInvalidTTL.
Variables ¶
var ( // ErrEmptyNamespace reports an empty cache namespace. ErrEmptyNamespace = errors.New("cache: namespace must not be empty") // ErrInvalidTTL reports a non-positive TTL other than NoExpiry, or an // entry that is already expired. ErrInvalidTTL = errors.New("cache: ttl must be positive") // ErrNilStore reports a nil or typed-nil store. ErrNilStore = errors.New("cache: store must not be nil") )
var ( ErrNilCoordinationBackend = errors.New("cache: coordination backend must not be nil") ErrEmptyCoordinationOwner = errors.New("cache: coordination owner must not be empty") ErrNilFillKeyFunc = errors.New("cache: fill key function must not be nil") ErrNilCoordinationLease = errors.New("cache: coordination backend returned a nil lease") )
Errors returned by NewCoordinationLocker and CoordinationLocker.Lock.
var ( ErrNoLayers = errors.New("cache: at least one layer is required") ErrNoInvalidationBus = errors.New("cache: no invalidation bus configured") ErrInvalidLowerLayer = errors.New("cache: lower layer must have at least one upper layer") )
Errors returned by layered-store constructors and ListenInvalidations.
var ( ErrLockNotAcquired = errors.New("cache: lock not acquired") ErrLeaseLost = errors.New("cache: lease is no longer owned") ErrFillLeaseLost = errors.New("cache: fill lease lost") ErrNilLease = errors.New("cache: locker returned a nil lease") )
Errors reported by lockers, leases and lease-guarded fills.
var ( ErrNilMessagingPublisher = errors.New("cache: messaging publisher must not be nil") ErrNilMessagingSubscriber = errors.New("cache: messaging subscriber must not be nil") ErrNilSubscriptionFactory = errors.New("cache: subscription factory must not be nil") )
Errors returned by NewMessagingInvalidationBus.
var ( ErrNilCache = errors.New("cache: wrapped cache must not be nil") ErrNilLoader = errors.New("cache: loader must not be nil") ErrNilLocker = errors.New("cache: locker must not be nil") ErrLoaderPanic = errors.New("cache: loader panicked") )
Errors returned by NewPullThrough and PullThroughCache.Get.
var ErrBatchLength = errors.New("cache: batch keys and values must have equal length")
ErrBatchLength reports batch arguments whose key and value slices differ in length.
var ErrNilInvalidationHandler = errors.New("cache: invalidation handler must not be nil")
ErrNilInvalidationHandler reports a nil handler passed to InvalidationBus.Subscribe.
var ErrUntypedValue = errors.New("cache: decoding an interface value requires a custom codec")
ErrUntypedValue reports a DefaultCodec decode into an interface type, whose concrete type cannot be recovered from the encoded bytes.
Functions ¶
This section is empty.
Types ¶
type BatchCache ¶
type BatchCache[K comparable, V any] interface { Cache[K, V] GetMany(context.Context, []K) ([]V, []bool, error) SetMany(context.Context, []K, []V) error SetManyWithTTL(context.Context, []K, []V, time.Duration) error InvalidateMany(context.Context, []K) error }
BatchCache is an optional Cache extension for multi-key operations. Results are positionally aligned with keys, and value slices must match the key slice length.
type BatchStore ¶
type BatchStore[K comparable, V any] interface { Store[K, V] GetMany(context.Context, string, []K) ([]Entry[V], []bool, error) SetMany(context.Context, string, []K, []Entry[V]) error InvalidateMany(context.Context, string, []K) error }
BatchStore is an optional Store extension for multi-key operations.
GetMany returns entries and presence flags positionally aligned with keys, applying the same visibility rules as Get. SetMany writes entries[i] under keys[i], returns ErrBatchLength when the slices differ in length, and lets a later duplicate key win. InvalidateMany removes every listed key and is idempotent for missing keys. Atomicity is backend-specific: unless an implementation documents otherwise, a failed call may have applied part of the batch.
type Cache ¶
type Cache[K comparable, V any] interface { Get(context.Context, K) (V, bool, error) Set(context.Context, K, V) error SetWithTTL(context.Context, K, V, time.Duration) error Invalidate(context.Context, K) error InvalidateAll(context.Context) error }
Cache is the typed cache API exposed to callers.
type Codec ¶
Codec converts a typed value to and from bytes for persistent stores.
func DefaultCodec ¶
DefaultCodec returns the automatic codec for T. Strings, byte slices, and scalar values use direct encodings; composite values use JSON. Encoded key identity is defined by the resulting bytes, so pointer keys encode their pointed-to value rather than their in-process pointer identity.
type CoordinationLocker ¶
type CoordinationLocker[K comparable] struct { // contains filtered or unexported fields }
CoordinationLocker is a Locker backed by any distributed-coordination Backend. Its leases implement ObservableLease. It is safe for concurrent use if the backend is.
func NewCoordinationLocker ¶
func NewCoordinationLocker[K comparable]( backend coordination.Backend, owner string, key FillKeyFunc[K], ) (*CoordinationLocker[K], error)
NewCoordinationLocker adapts backend into a Locker that acquires leases as owner under keys derived by key. It returns ErrNilCoordinationBackend, ErrEmptyCoordinationOwner or ErrNilFillKeyFunc for missing dependencies.
func (*CoordinationLocker[K]) Lock ¶
func (l *CoordinationLocker[K]) Lock( ctx context.Context, namespace string, key K, ttl time.Duration, ) (Lease, error)
Lock acquires a lease for the fill key of (namespace, key), waiting as the backend's Acquire with Wait set does. Contention is reported as ErrLockNotAcquired and a lost or foreign lease as ErrLeaseLost, each joined with the backend error.
type Entry ¶
Entry is the value and logical freshness metadata exchanged with stores. Found is false for an authoritative negative-cache entry. A zero ExpiresAt marks an entry that never expires; stores must neither hide it as expired nor attach a backend-native TTL to it.
func (Entry[V]) Expired ¶
Expired reports whether the entry is logically expired at now. Entries without an expiration are never expired.
func (Entry[V]) NeverExpires ¶
NeverExpires reports whether the entry has no expiration (zero ExpiresAt).
type EntryCache ¶
type EntryCache[K comparable, V any] interface { Cache[K, V] GetEntry(context.Context, K) (Entry[V], bool, error) SetEntry(context.Context, K, Entry[V]) error }
EntryCache is an optional Cache extension that exposes stored entries, including negative entries and their expiration.
type FillKeyFunc ¶
type FillKeyFunc[K comparable] func(namespace string, key K) (string, error)
FillKeyFunc derives the coordination lease key for a cache key. It must be deterministic and injective over the complete (namespace, key) tuple and stable across deployments, or different keys may share one lease.
type InvalidationBus ¶
type InvalidationBus[K comparable] interface { Publish(context.Context, InvalidationEvent[K]) error Subscribe(context.Context, string, InvalidationHandler[K]) error }
InvalidationBus publishes and subscribes to cache invalidation events.
type InvalidationEvent ¶
type InvalidationEvent[K comparable] struct { Namespace string Kind InvalidationKind Key K Generation uint64 }
InvalidationEvent is sent between cache workers after a mutation.
type InvalidationHandler ¶
type InvalidationHandler[K comparable] func(context.Context, InvalidationEvent[K]) error
InvalidationHandler applies a remotely published invalidation event.
type InvalidationKind ¶
type InvalidationKind uint8
InvalidationKind identifies the scope of an invalidation event.
const ( // InvalidateKey invalidates one key in a namespace. InvalidateKey InvalidationKind = iota + 1 // InvalidateNamespace invalidates every key in a namespace. InvalidateNamespace )
type LayeredOption ¶
type LayeredOption func(*layeredConfig)
LayeredOption configures layered-store behavior.
func WithLayerObserver ¶
func WithLayerObserver(observer Observer) LayeredOption
WithLayerObserver reports errors skipped by fail-open reads and promotions.
func WithStrictLayerReads ¶
func WithStrictLayerReads() LayeredOption
WithStrictLayerReads makes the first read error abort the lookup.
type LayeredStore ¶
type LayeredStore[K comparable, V any] struct { // contains filtered or unexported fields }
LayeredStore composes stores ordered from fastest to slowest.
func NewLayered ¶
func NewLayered[K comparable, V any](layers []Store[K, V], options ...LayeredOption) (*LayeredStore[K, V], error)
NewLayered constructs a store from a fastest-to-slowest layer list.
Example ¶
package main
import (
"context"
"fmt"
cache "github.com/justusschock/cache"
"github.com/justusschock/cache/backend/memory"
)
type User struct {
ID string
Name string
}
func main() {
fast := memory.New[string, User]()
defer func() { _ = fast.Close() }()
shared := memory.New[string, User]()
defer func() { _ = shared.Close() }()
layers, err := cache.NewLayered([]cache.Store[string, User]{fast, shared})
if err != nil {
panic(err)
}
ctx := context.Background()
entry := cache.Entry[User]{Value: User{ID: "user-42", Name: "Ada"}, Found: true}
if err := shared.Set(ctx, "users", "user-42", entry); err != nil {
panic(err)
}
// A lower-layer hit is promoted into the faster layer.
if _, _, err := layers.Get(ctx, "users", "user-42"); err != nil {
panic(err)
}
promoted, present, err := fast.Get(ctx, "users", "user-42")
if err != nil {
panic(err)
}
fmt.Println(present, promoted.Value.Name)
}
Output: true Ada
func NewLayeredWithInvalidationBus ¶
func NewLayeredWithInvalidationBus[K comparable, V any](layers []Store[K, V], bus InvalidationBus[K], options ...LayeredOption) (*LayeredStore[K, V], error)
NewLayeredWithInvalidationBus constructs a layered store that publishes invalidations.
func (*LayeredStore[K, V]) Get ¶
func (s *LayeredStore[K, V]) Get(ctx context.Context, namespace string, key K) (Entry[V], bool, error)
Get reads layers from fastest to slowest and returns the first entry found, promoting it unchanged into every faster layer that missed. A layer error is reported to the Observer and treated as a miss, unless WithStrictLayerReads is set, in which case it is returned.
func (*LayeredStore[K, V]) Invalidate ¶
func (s *LayeredStore[K, V]) Invalidate(ctx context.Context, namespace string, key K) error
Invalidate removes key from every layer, joining the errors, and publishes a key-scoped event when an invalidation bus is configured.
func (*LayeredStore[K, V]) InvalidateAll ¶
func (s *LayeredStore[K, V]) InvalidateAll(ctx context.Context, namespace string) error
InvalidateAll removes namespace from every layer, joining the errors, and publishes a namespace-scoped event when an invalidation bus is configured.
func (*LayeredStore[K, V]) ListenInvalidations ¶
func (s *LayeredStore[K, V]) ListenInvalidations(ctx context.Context, namespace string, lowerLayer int) error
ListenInvalidations applies bus events to layers above lowerLayer. The lower layer itself is not touched because it is the event's source of truth.
func (*LayeredStore[K, V]) Set ¶
func (s *LayeredStore[K, V]) Set(ctx context.Context, namespace string, key K, entry Entry[V]) error
Set writes entry to the slowest layer first and then to each faster layer. A slowest-layer failure stops the write; faster-layer failures are joined. With an invalidation bus, a key-scoped event is published afterwards.
type Lease ¶
type Lease interface {
Refresh(context.Context, time.Duration) error
Release(context.Context) error
}
Lease is a renewable distributed lock held by the caller.
type Locker ¶
type Locker[K comparable] interface { Lock(context.Context, string, K, time.Duration) (Lease, error) }
Locker coordinates cache fills for one namespaced key.
type MessagingInvalidationBus ¶
type MessagingInvalidationBus[K comparable] struct { // contains filtered or unexported fields }
MessagingInvalidationBus is an InvalidationBus over typed messaging publishers and subscribers. It is safe for concurrent use if they are.
func NewMessagingInvalidationBus ¶
func NewMessagingInvalidationBus[K comparable]( publisher messaging.Publisher[InvalidationEvent[K]], subscriber messaging.Subscriber[InvalidationEvent[K]], factory SubscriptionFactory, ) (*MessagingInvalidationBus[K], error)
NewMessagingInvalidationBus constructs a bus that publishes to and subscribes on the subscription that factory returns for each namespace.
func (*MessagingInvalidationBus[K]) Publish ¶
func (b *MessagingInvalidationBus[K]) Publish(ctx context.Context, event InvalidationEvent[K]) error
Publish wraps event in an envelope addressed to the subject of its namespace's subscription and publishes it.
func (*MessagingInvalidationBus[K]) Subscribe ¶
func (b *MessagingInvalidationBus[K]) Subscribe( ctx context.Context, namespace string, handler InvalidationHandler[K], ) error
Subscribe follows the messaging subscriber lifetime and normally blocks until ctx ends. Handled deliveries and deliveries for another namespace are acknowledged; handler failures are negatively acknowledged so that an at-least-once transport redelivers them.
type ObservableLease ¶
type ObservableLease interface {
Lease
Done() <-chan struct{}
}
ObservableLease is a Lease that reports loss of ownership by closing the channel returned by Done.
type PullThroughCache ¶
type PullThroughCache[K comparable, V any] struct { // contains filtered or unexported fields }
PullThroughCache loads and stores values on cache misses.
func NewPullThrough ¶
func NewPullThrough[K comparable, V any](namespace string, wrapped Cache[K, V], loader Loader[K, V], options ...PullThroughOption[K]) (*PullThroughCache[K, V], error)
NewPullThrough wraps a cache with automatic miss loading.
Example ¶
package main
import (
"context"
"fmt"
"time"
cache "github.com/justusschock/cache"
"github.com/justusschock/cache/backend/memory"
)
type User struct {
ID string
Name string
}
func main() {
store := memory.New[string, User]()
defer func() { _ = store.Close() }()
users, err := cache.New("users", 5*time.Minute, store)
if err != nil {
panic(err)
}
loads := 0
loaded, err := cache.NewPullThrough(
"users",
users,
func(_ context.Context, id string) (User, bool, error) {
loads++
if id != "user-42" {
return User{}, false, nil // authoritative miss, cached negatively
}
return User{ID: id, Name: "Ada"}, true, nil
},
cache.WithNegativeTTL[string](30*time.Second),
)
if err != nil {
panic(err)
}
ctx := context.Background()
for range 2 {
user, found, err := loaded.Get(ctx, "user-42")
if err != nil {
panic(err)
}
fmt.Println(found, user.Name)
}
_, found, err := loaded.Get(ctx, "user-7")
if err != nil {
panic(err)
}
fmt.Println(found, "loads:", loads)
}
Output: true Ada true Ada false loads: 2
func (*PullThroughCache[K, V]) Get ¶
func (c *PullThroughCache[K, V]) Get(ctx context.Context, key K) (V, bool, error)
Get returns the cached value for key, loading it on a miss. Concurrent misses for one key share a single load; each caller waits with its own ctx, and the load is canceled once every waiter has left. Authoritative misses are cached for the negative TTL when the wrapped cache is an EntryCache; loader errors are never cached.
func (*PullThroughCache[K, V]) Invalidate ¶
func (c *PullThroughCache[K, V]) Invalidate(ctx context.Context, key K) error
Invalidate delegates to the wrapped cache.
func (*PullThroughCache[K, V]) InvalidateAll ¶
func (c *PullThroughCache[K, V]) InvalidateAll(ctx context.Context) error
InvalidateAll delegates to the wrapped cache.
func (*PullThroughCache[K, V]) Set ¶
func (c *PullThroughCache[K, V]) Set(ctx context.Context, key K, value V) error
Set delegates to the wrapped cache.
func (*PullThroughCache[K, V]) SetWithTTL ¶
func (c *PullThroughCache[K, V]) SetWithTTL(ctx context.Context, key K, value V, ttl time.Duration) error
SetWithTTL delegates to the wrapped cache.
type PullThroughOption ¶
type PullThroughOption[K comparable] func(*pullThroughConfig[K]) error
PullThroughOption configures pull-through behavior.
func WithLoadOnLockError ¶
func WithLoadOnLockError[K comparable]() PullThroughOption[K]
WithLoadOnLockError permits loading when the distributed locker fails.
func WithLockPollInterval ¶
func WithLockPollInterval[K comparable](interval time.Duration) PullThroughOption[K]
WithLockPollInterval controls how often a contended lock is retried.
func WithLocker ¶
func WithLocker[K comparable](locker Locker[K], leaseTTL time.Duration) PullThroughOption[K]
WithLocker enables distributed miss coordination using renewable leases.
func WithNegativeTTL ¶
func WithNegativeTTL[K comparable](ttl time.Duration) PullThroughOption[K]
WithNegativeTTL sets the lifetime of authoritative not-found entries.
func WithStrictPullThroughReads ¶
func WithStrictPullThroughReads[K comparable]() PullThroughOption[K]
WithStrictPullThroughReads returns cache read errors instead of loading.
type StandardCache ¶
type StandardCache[K comparable, V any] struct { // contains filtered or unexported fields }
StandardCache applies namespace and TTL policy to a Store.
func New ¶
func New[K comparable, V any](namespace string, defaultTTL time.Duration, store Store[K, V]) (*StandardCache[K, V], error)
New constructs a cache with a required namespace and positive default TTL. Pass NoExpiry as defaultTTL to make Set and SetMany write entries that never expire.
func (*StandardCache[K, V]) Get ¶
func (c *StandardCache[K, V]) Get(ctx context.Context, key K) (V, bool, error)
Get returns the value cached under key and whether it was found. Missing, expired and negative entries report found as false.
func (*StandardCache[K, V]) GetEntry ¶
GetEntry returns the entry stored under key, including negative entries, and whether a live entry is present. Expired entries are reported absent.
func (*StandardCache[K, V]) GetMany ¶
func (c *StandardCache[K, V]) GetMany(ctx context.Context, keys []K) ([]V, []bool, error)
GetMany looks up keys and returns values and found flags aligned with keys. Missing, expired, and negative entries report found as false. It uses a single BatchStore call when the store supports batching and otherwise falls back to one Get per key.
Example ¶
package main
import (
"context"
"fmt"
cache "github.com/justusschock/cache"
"github.com/justusschock/cache/backend/memory"
)
func main() {
store := memory.New[string, int]()
defer func() { _ = store.Close() }()
sizes, err := cache.New("file-sizes", cache.NoExpiry, store)
if err != nil {
panic(err)
}
ctx := context.Background()
if err := sizes.SetMany(ctx, []string{"a.txt", "b.txt"}, []int{10, 20}); err != nil {
panic(err)
}
values, found, err := sizes.GetMany(ctx, []string{"b.txt", "missing.txt", "a.txt"})
if err != nil {
panic(err)
}
fmt.Println(values, found)
}
Output: [20 0 10] [true false true]
func (*StandardCache[K, V]) Invalidate ¶
func (c *StandardCache[K, V]) Invalidate(ctx context.Context, key K) error
Invalidate removes key. Removing a missing key is not an error.
func (*StandardCache[K, V]) InvalidateAll ¶
func (c *StandardCache[K, V]) InvalidateAll(ctx context.Context) error
InvalidateAll removes every key in the cache's namespace.
func (*StandardCache[K, V]) InvalidateMany ¶
func (c *StandardCache[K, V]) InvalidateMany(ctx context.Context, keys []K) error
InvalidateMany removes keys. It uses a single BatchStore call when the store supports batching and otherwise falls back to one Invalidate per key, stopping at the first error.
func (*StandardCache[K, V]) Set ¶
func (c *StandardCache[K, V]) Set(ctx context.Context, key K, value V) error
Set stores value under key with the cache's default TTL.
func (*StandardCache[K, V]) SetEntry ¶
func (c *StandardCache[K, V]) SetEntry(ctx context.Context, key K, entry Entry[V]) error
SetEntry stores entry as-is. It rejects entries that are already expired; a zero ExpiresAt stores an entry that never expires.
func (*StandardCache[K, V]) SetMany ¶
func (c *StandardCache[K, V]) SetMany(ctx context.Context, keys []K, values []V) error
SetMany stores values[i] under keys[i] with the default TTL.
func (*StandardCache[K, V]) SetManyWithTTL ¶
func (c *StandardCache[K, V]) SetManyWithTTL(ctx context.Context, keys []K, values []V, ttl time.Duration) error
SetManyWithTTL stores values[i] under keys[i] for ttl, or without expiration when ttl is NoExpiry. It uses a single BatchStore call when the store supports batching and otherwise falls back to one Set per key, stopping at the first error.
func (*StandardCache[K, V]) SetWithTTL ¶
func (c *StandardCache[K, V]) SetWithTTL(ctx context.Context, key K, value V, ttl time.Duration) error
SetWithTTL stores value for ttl, or without expiration when ttl is NoExpiry.
type Store ¶
type Store[K comparable, V any] interface { Get(context.Context, string, K) (Entry[V], bool, error) Set(context.Context, string, K, Entry[V]) error Invalidate(context.Context, string, K) error InvalidateAll(context.Context, string) error }
Store persists typed entries for one or more namespaces.
type SubscriptionFactory ¶
type SubscriptionFactory func(namespace string) messaging.Subscription
SubscriptionFactory maps a namespace to the deterministic subscription used for both publishing and subscribing. In particular, Subject must be stable.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
backend
|
|
|
disk
Package disk provides a persistent bbolt-backed cache store.
|
Package disk provides a persistent bbolt-backed cache store. |
|
dragonfly
Package dragonfly provides a Dragonfly-backed cache store through its Redis protocol.
|
Package dragonfly provides a Dragonfly-backed cache store through its Redis protocol. |
|
hazelcast
Package hazelcast provides a Hazelcast IMap-backed cache store.
|
Package hazelcast provides a Hazelcast IMap-backed cache store. |
|
memcached
Package memcached provides a Memcached-backed cache store.
|
Package memcached provides a Memcached-backed cache store. |
|
memory
Package memory provides a race-safe in-process cache store.
|
Package memory provides a race-safe in-process cache store. |
|
postgres
Package postgres provides a PostgreSQL-backed cache store.
|
Package postgres provides a PostgreSQL-backed cache store. |
|
redis
Package redis provides a Redis-backed cache store.
|
Package redis provides a Redis-backed cache store. |
|
valkey
Package valkey provides a Valkey-backed cache store.
|
Package valkey provides a Valkey-backed cache store. |
|
Package cachetest provides conformance suites for implementations of the cache store and invalidation-bus interfaces.
|
Package cachetest provides conformance suites for implementations of the cache store and invalidation-bus interfaces. |
|
internal
|
|
|
wire
Package wire implements the persistent entry envelope and the invalidation message format shared by the serialized backends.
|
Package wire implements the persistent entry envelope and the invalidation message format shared by the serialized backends. |