Documentation
¶
Overview ¶
Package redcache is a typed cache-aside for Redis, built on the rueidis client. It combines rueidis client-side caching with distributed SET NX locking so that, across every process, only one caller populates a missing key while the rest wait on the invalidation push for the populated value — a stampede-resistant cache behind a single Cache whose operations infer their key and value types per call.
How it works ¶
A read registers an in-process lock entry, then issues a client-side-cached GET. That GET serves a dual purpose: it returns any cached value and subscribes the connection to Redis invalidation for the key. On a miss, one caller wins a distributed lock (SET NX with a UUIDv7 value), runs the loader, and atomically replaces the lock with the real value via a Lua CAS. Every other caller — in this process or another — waits for the resulting invalidation, with jittered polling as a fallback until the lock TTL, and then reads the populated value. In-process leader/follower coordination collapses a thundering herd on one key to a single Redis SET NX.
Constructing a cache ¶
Open one Conn (it owns the rueidis client and invalidation stream), then construct caches over it that all share that client:
- New — a Cache with StringKeyCodec (string, ~string, TextMarshaler keys).
- NewKeyed — a Cache with an explicit KeyCodec for other key types.
- NewBytes — a Cache with UnsafeBytesCodec for zero-copy []byte values.
A Cache owns one KeyCodec and one Codec. Its generic methods infer K from the key and V from the loader or value on every call, so one JSON-backed Cache can store different Go types under keys of different Go types. Cache.Peek requires an explicit value type because it has no loader or value argument from which Go can infer one. Lifecycle (Close) and raw-client access (Client) live on the Conn.
There is no interface form (generic methods cannot satisfy Go interfaces); code under test takes a *Cache and builds it over OpenMemory, an in-process Conn, instead of Redis.
Minimal example ¶
conn, err := redcache.Open(
rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
)
if err != nil {
return err
}
defer conn.Close()
cache := redcache.New(conn, redcache.StringCodec{})
v, err := cache.Get(ctx, time.Minute, "k", func(ctx context.Context, key string) (string, error) {
return loadFromUpstream(ctx, key) // runs only on a miss, once per key
})
Beyond read-through ¶
Every Cache also supports write-through priming — Set, ForceSet, and Touch (with Multi variants) — for populating or extending entries without a read-through miss. Opt into background refresh of stale-but-valid entries with WithRefreshAfterFraction (and WithRefreshBeta for XFetch-style probabilistic early expiration). Wire counters through WithMetrics.
Values, codecs, and absence ¶
Values are stored through a Codec; keys through a KeyCodec. JSONCodec is the typical choice; StringCodec and UnsafeBytesCodec are identity codecs. The string path is safe to retain because strings are immutable; the bytes path is zero-copy and returns borrowed memory. Decode failures on read are wrapped with ErrDecode. Absence semantics are the caller's to own — there is no ErrNotFound sentinel; cache a *T, sql.Null[T], or a domain sentinel inside V to represent "not found" and avoid cache penetration.
Index ¶
- Constants
- Variables
- type BatchKeyError
- type Cache
- func (c *Cache) Del[K comparable](ctx context.Context, k K) error
- func (c *Cache) DelMulti[K comparable](ctx context.Context, keys []K) error
- func (c *Cache) ForceSet[K comparable, V any](ctx context.Context, ttl time.Duration, k K, v V) error
- func (c *Cache) ForceSetMulti[K comparable, V any](ctx context.Context, ttl time.Duration, values map[K]V) error
- func (c *Cache) Get[K comparable, V any](ctx context.Context, ttl time.Duration, k K, ...) (V, error)
- func (c *Cache) GetMulti[K comparable, V any](ctx context.Context, ttl time.Duration, keys []K, ...) (map[K]V, error)
- func (c *Cache) Peek[K comparable, V any](ctx context.Context, ttl time.Duration, k K) (V, bool, error)
- func (c *Cache) Set[K comparable, V any](ctx context.Context, ttl time.Duration, k K, ...) error
- func (c *Cache) SetMulti[K comparable, V any](ctx context.Context, ttl time.Duration, keys []K, ...) error
- func (c *Cache) Touch[K comparable](ctx context.Context, ttl time.Duration, k K) error
- func (c *Cache) TouchMulti[K comparable](ctx context.Context, ttl time.Duration, keys []K) error
- type Codec
- type Conn
- type JSONCodec
- type JSONV2Codec
- type KeyCodec
- type KeyCodecFunc
- type Logger
- type MemoryOption
- type Metrics
- type NoopMetrics
- func (NoopMetrics) CacheHits(int64)
- func (NoopMetrics) CacheMisses(int64)
- func (NoopMetrics) InvalidationError()
- func (NoopMetrics) LoaderDuration(time.Duration)
- func (NoopMetrics) LoaderErrors(int64)
- func (NoopMetrics) LockContended(int64)
- func (NoopMetrics) LockLost(string)
- func (NoopMetrics) LockWaitDuration(time.Duration)
- func (NoopMetrics) RedisError(string)
- func (NoopMetrics) RefreshDropped(int64)
- func (NoopMetrics) RefreshError(string)
- func (NoopMetrics) RefreshPanicked(string)
- func (NoopMetrics) RefreshSkipped(int64)
- func (NoopMetrics) RefreshTriggered(int64)
- type Option
- func WithClientBuilder(b func(option rueidis.ClientOption) (rueidis.Client, error)) Option
- func WithLockPrefix(p string) Option
- func WithLockTTL(d time.Duration) Option
- func WithLogger(l Logger) Option
- func WithMetrics(m Metrics) Option
- func WithRefreshAfterFraction(f float64) Option
- func WithRefreshBeta(b float64) Option
- func WithRefreshLockPrefix(p string) Option
- func WithRefreshQueueSize(n int) Option
- func WithRefreshTimeout(d time.Duration) Option
- func WithRefreshWorkers(n int) Option
- type StringCodec
- type StringKeyCodec
- type UnsafeBytesCodec
Examples ¶
Constants ¶
const ( // DefaultLockPrefix tags in-Redis lock values so reads recognise a lock as // a miss. DefaultLockPrefix = "__redcache:lock:" // DefaultRefreshPrefix prefixes refresh-ahead dedup lock keys. DefaultRefreshPrefix = "__redcache:refresh:" )
Variables ¶
var ErrDecode = errors.New("decode failed")
ErrDecode is returned (wrapped) from typed reads when a stored value cannot be decoded. The library does not auto-evict — the caller decides whether to log, Del, or retry.
var ErrInvalidTTL = errors.New("redcache: ttl must be at least 1ms; use Del to remove")
ErrInvalidTTL is returned by TTL-bearing methods when ttl is under one millisecond, the resolution of Redis PX (which rejects PX 0); use Del to remove an entry.
var ErrLockLost = errors.New("lock was lost or expired before value could be set")
ErrLockLost is returned when the distributed lock was stolen or expired before the value could be written.
var ErrMissingValue = errors.New("redcache: loader returned no value for key")
ErrMissingValue is returned (wrapped, naming the keys) when a GetMulti or SetMulti loader returns no value for a key it was given. Loaders must return every key; encode a known-absent entity as a value (e.g. a tombstone).
Functions ¶
This section is empty.
Types ¶
type BatchKeyError ¶ added in v0.3.0
type BatchKeyError[K comparable] struct { Failed map[K]error Succeeded []K }
BatchKeyError is the typed, key-preserving error returned via errors.As from the multi-key write methods (SetMulti, ForceSetMulti) on partial failure. K is the operation's key type (the element type of its keys, or the key type of its values map), not a property of the Cache: match it with that same K. Unwrap exposes every per-key error to errors.Is and errors.As. All accessors are nil-safe.
func (*BatchKeyError[K]) Error ¶ added in v0.3.0
func (e *BatchKeyError[K]) Error() string
Error formats the batch outcome with failed keys sorted by their %v rendering for stable output.
func (*BatchKeyError[K]) ErrorFor ¶ added in v0.3.0
func (e *BatchKeyError[K]) ErrorFor(k K) error
ErrorFor returns the error for k, or nil.
func (*BatchKeyError[K]) HasError ¶ added in v0.3.0
func (e *BatchKeyError[K]) HasError(k K) bool
HasError reports whether k failed.
func (*BatchKeyError[K]) HasFailures ¶ added in v0.3.0
func (e *BatchKeyError[K]) HasFailures() bool
HasFailures reports whether any key failed.
func (*BatchKeyError[K]) Unwrap ¶ added in v0.4.0
func (e *BatchKeyError[K]) Unwrap() []error
Unwrap returns the per-key errors, so errors.Is(err, context.Canceled) or errors.Is(err, ErrLockLost) matches when any key failed that way.
type Cache ¶ added in v0.3.0
type Cache struct {
// contains filtered or unexported fields
}
Cache is a cache-aside handle. It owns one KeyCodec and one value Codec; every operation infers its key and value types independently, so a single Cache can store different Go types under keys of different Go types. Codec compatibility with each operation's K and V is checked by the codecs at call time. Lifecycle and raw-client access remain on the owning Conn.
func New ¶ added in v0.3.0
New constructs a Cache over c with StringKeyCodec and the given value codec. It does no I/O. Passing a nil codec panics because it is a programmer error.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/redis/rueidis"
"github.com/dcbickfo/redcache"
)
func main() {
conn, err := redcache.Open(
rueidis.ClientOption{
InitAddress: []string{"127.0.0.1:6379"},
},
redcache.WithLockTTL(5*time.Second),
)
if err != nil {
panic(err)
}
defer conn.Close()
client := redcache.New(conn, redcache.StringCodec{})
val, err := client.Get(context.Background(), time.Minute, "example:get", func(ctx context.Context, key string) (string, error) {
// Called only on cache miss — fetch from your data source.
return "hello", nil
})
if err != nil {
panic(err)
}
fmt.Println(val)
// This example dials Redis, so it omits an Output: directive (which would
// make `go test` run it). It is compiled to keep the snippet honest.
}
Output:
Example (GetMulti) ¶
package main
import (
"context"
"fmt"
"time"
"github.com/redis/rueidis"
"github.com/dcbickfo/redcache"
)
func main() {
conn, err := redcache.Open(
rueidis.ClientOption{
InitAddress: []string{"127.0.0.1:6379"},
},
redcache.WithLockTTL(5*time.Second),
)
if err != nil {
panic(err)
}
defer conn.Close()
client := redcache.New(conn, redcache.StringCodec{})
keys := []string{"example:multi:a", "example:multi:b"}
vals, err := client.GetMulti(context.Background(), time.Minute, keys, func(ctx context.Context, keys []string) (map[string]string, error) {
// Called only for keys not in cache — fetch from your data source.
result := make(map[string]string, len(keys))
for _, k := range keys {
result[k] = "value-for-" + k
}
return result, nil
})
if err != nil {
panic(err)
}
fmt.Println(len(vals))
// Redis-dependent; omits Output: so `go test` does not run it.
}
Output:
func NewBytes ¶ added in v0.3.0
NewBytes is New with UnsafeBytesCodec preset. Decoded byte slices alias borrowed cache memory and must not be mutated or retained after the call.
func NewKeyed ¶ added in v0.4.0
NewKeyed is New with an explicit KeyCodec, for key types StringKeyCodec does not handle.
Example ¶
NewKeyed keys the cache by a non-string domain type via a KeyCodec. KeyCodecFunc adapts a plain function into a KeyCodec.
package main
import (
"context"
"fmt"
"time"
"github.com/redis/rueidis"
"github.com/dcbickfo/redcache"
)
func main() {
type UserID int64
type User struct {
ID UserID
Name string
}
userIDCodec := redcache.KeyCodecFunc[UserID](func(id UserID) (string, error) {
return fmt.Sprintf("user:%d", id), nil
})
conn, err := redcache.Open(
rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
redcache.WithLockTTL(5*time.Second),
)
if err != nil {
panic(err)
}
defer conn.Close()
cache := redcache.NewKeyed(conn, userIDCodec, redcache.JSONCodec{})
u, err := cache.Get(context.Background(), time.Minute, UserID(123),
func(ctx context.Context, id UserID) (User, error) {
// Load from your data source; runs only on a miss.
return User{ID: id, Name: "alice"}, nil
},
)
if err != nil {
panic(err)
}
fmt.Println(u.Name)
}
Output:
func (*Cache) Del ¶ added in v0.3.0
func (c *Cache) Del[K comparable](ctx context.Context, k K) error
Del removes k and triggers invalidation on subscribed clients.
func (*Cache) DelMulti ¶ added in v0.3.0
func (c *Cache) DelMulti[K comparable](ctx context.Context, keys []K) error
DelMulti removes keys and triggers invalidation on subscribed clients.
func (*Cache) ForceSet ¶ added in v0.3.0
func (c *Cache) ForceSet[K comparable, V any](ctx context.Context, ttl time.Duration, k K, v V) error
ForceSet writes v unconditionally, bypassing locks. V is inferred from v. In-progress Get callers on the same key retry and observe the new value; in-progress Set callers receive ErrLockLost and abandon their pending write.
Example ¶
ForceSet writes a value unconditionally, bypassing the lock. Any in-progress Get or Set on the same key sees ErrLockLost and retries. Redis-dependent, so it omits an Output: directive.
package main
import (
"context"
"fmt"
"time"
"github.com/redis/rueidis"
"github.com/dcbickfo/redcache"
)
func main() {
conn, err := redcache.Open(
rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
redcache.WithLockTTL(5*time.Second),
)
if err != nil {
panic(err)
}
defer conn.Close()
cache := redcache.New(conn, redcache.StringCodec{})
if err := cache.ForceSet(context.Background(), time.Minute, "config:greeting", "hola"); err != nil {
panic(err)
}
fmt.Println("forced")
}
Output:
func (*Cache) ForceSetMulti ¶ added in v0.3.0
func (c *Cache) ForceSetMulti[K comparable, V any](ctx context.Context, ttl time.Duration, values map[K]V) error
ForceSetMulti writes values unconditionally. K and V are inferred from values; pass them explicitly when values is an untyped nil map. Encode failures are collected per key and successful entries are still written; partial failures surface as *BatchKeyError[K].
Example ¶
Multi-key writes report per-key partial failures as *BatchKeyError[K], reachable via errors.As. Note the generic type argument on the target pointer: it must match the cache's key type (string here).
package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/redis/rueidis"
"github.com/dcbickfo/redcache"
)
// failOnEmpty is a value codec that refuses to encode the empty string, used to
// force a deterministic per-key failure in the ForceSetMulti example.
type failOnEmpty struct{}
func (failOnEmpty) Encode(v any) ([]byte, error) {
s, ok := v.(string)
if !ok {
return nil, fmt.Errorf("failOnEmpty cannot encode %T", v)
}
if s == "" {
return nil, errors.New("empty value not allowed")
}
return []byte(s), nil
}
func (failOnEmpty) Decode(b []byte, dst any) error {
p, ok := dst.(*string)
if !ok {
return fmt.Errorf("failOnEmpty cannot decode into %T", dst)
}
*p = string(b)
return nil
}
func main() {
conn, err := redcache.Open(
rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
)
if err != nil {
panic(err)
}
defer conn.Close()
cache := redcache.New(conn, failOnEmpty{})
err = cache.ForceSetMulti(context.Background(), time.Minute, map[string]string{
"a": "alpha",
"b": "", // fails to encode
})
if be, ok := errors.AsType[*redcache.BatchKeyError[string]](err); ok {
fmt.Println("b failed:", be.HasError("b"))
fmt.Println("a succeeded:", !be.HasError("a"))
for k, kerr := range be.Failed {
_ = k
_ = kerr // handle each failed key
}
}
}
Output:
func (*Cache) Get ¶ added in v0.3.0
func (c *Cache) Get[K comparable, V any]( ctx context.Context, ttl time.Duration, k K, fn func(context.Context, K) (V, error), ) (V, error)
Get returns the cached value for k, calling fn on a miss. Only one caller across all processes runs fn for a given key; the rest wait on invalidation. V is inferred from fn. Decode errors are wrapped with ErrDecode.
func (*Cache) GetMulti ¶ added in v0.3.0
func (c *Cache) GetMulti[K comparable, V any]( ctx context.Context, ttl time.Duration, keys []K, fn func(context.Context, []K) (map[K]V, error), ) (map[K]V, error)
GetMulti returns cached values for keys, calling fn for misses. V is inferred from fn. fn must return a value for every key it is given; an omitted key fails the call with ErrMissingValue. Each phase is one pipeline, which the cluster client splits per node; a decode error aborts the batch and is wrapped with ErrDecode.
func (*Cache) Peek ¶ added in v0.3.0
func (c *Cache) Peek[K comparable, V any](ctx context.Context, ttl time.Duration, k K) (V, bool, error)
Peek is a read-only, client-side-cached lookup with no loader and no lock. The caller must supply both K and V (as Peek[K, V]) because Peek has no value argument from which Go can infer V. It returns (value, true, nil) on a hit, (zero, false, nil) on a miss or lock value, and (zero, false, err) on a Redis or decode error. ttl is the client-side-cache subscription TTL, like Get.
func (*Cache) Set ¶ added in v0.3.0
func (c *Cache) Set[K comparable, V any]( ctx context.Context, ttl time.Duration, k K, fn func(context.Context, K) (V, error), ) error
Set populates k via fn under a write lock, writing the value to every subscribed client. V is inferred from fn. On callback error the prior value is restored.
Example ¶
Set primes a key under a write lock without a prior read. If the callback returns an error, the cache restores the value that was there before, so a failed refresh never leaves the key empty. Redis-dependent, so it omits an Output: directive and is compiled but not run by `go test`.
package main
import (
"context"
"fmt"
"time"
"github.com/redis/rueidis"
"github.com/dcbickfo/redcache"
)
func main() {
conn, err := redcache.Open(
rueidis.ClientOption{InitAddress: []string{"127.0.0.1:6379"}},
redcache.WithLockTTL(5*time.Second),
)
if err != nil {
panic(err)
}
defer conn.Close()
cache := redcache.New(conn, redcache.StringCodec{})
err = cache.Set(context.Background(), time.Minute, "config:greeting",
func(ctx context.Context, key string) (string, error) {
// Compute the value to cache; runs under a write lock.
return "hello", nil
},
)
if err != nil {
panic(err)
}
fmt.Println("primed")
}
Output:
func (*Cache) SetMulti ¶ added in v0.3.0
func (c *Cache) SetMulti[K comparable, V any]( ctx context.Context, ttl time.Duration, keys []K, fn func(context.Context, []K) (map[K]V, error), ) error
SetMulti populates keys via fn under write locks. V is inferred from fn. Partial failures surface as *BatchKeyError[K] via errors.As; a key fn omits is restored to its prior value and fails with ErrMissingValue.
func (*Cache) Touch ¶ added in v0.3.0
Touch updates the TTL of a cached value. It is a no-op for a missing key or lock value. Clients caching the key are invalidated and re-fetch it with the new TTL on their next read.
func (*Cache) TouchMulti ¶ added in v0.3.0
TouchMulti updates the TTL of cached values, with the same behavior as Touch.
type Codec ¶ added in v0.3.0
Codec encodes and decodes values into the envelope payload. A Cache owns one Codec and may use it with different value types across operations. Decode writes into the supplied destination; the cache never asserts a decoded interface value back to the operation's type. Implementations must be concurrent-safe and return an error for unsupported value or destination types.
Ownership of return values:
- Encode's returned slice is handed to the library and must not be mutated by the caller afterward. The library may alias it without copying, so the codec must not retain or later modify it either.
- Decode receives a pointer to the operation's value type. Its input slice is borrowed from library-internal memory and is only valid for the duration of the call; it must not be retained.
Identity codecs (UnsafeBytesCodec) alias this borrowed memory directly and so trade safety for zero copies — the decoded []byte must not outlive the call or be mutated. JSONCodec returns owned decoded values. StringCodec returns immutable strings that are safe to retain.
type Conn ¶ added in v0.3.0
type Conn struct {
// contains filtered or unexported fields
}
Conn owns one rueidis client, its invalidation stream, and a lock namespace. Every Cache derived from it shares the single client and invalidation subscription. Lifecycle stays on the Conn: open it once and close it when done with all derived caches.
func Open ¶ added in v0.3.0
func Open(clientOption rueidis.ClientOption, opts ...Option) (*Conn, error)
Open builds a Conn with its own rueidis.Client (wired for invalidation). Construct caches over it with New, NewKeyed, or NewBytes.
func OpenMemory ¶ added in v0.4.0
func OpenMemory(opts ...MemoryOption) *Conn
OpenMemory returns a Conn backed by an in-process map instead of Redis, for unit tests and local development. Caches built over it (New, NewKeyed, NewBytes) behave identically at the typed layer — codecs run, TTLs expire, a present entry is a hit, a miss calls the loader, and loader results for keys nobody asked for are dropped — but there is no single-flight (concurrent misses each call the loader), no distributed locking, invalidation, refresh-ahead, or metrics, and Client() returns nil. It never fails and needs no Close.
type JSONCodec ¶ added in v0.3.0
type JSONCodec struct{}
JSONCodec encodes values via encoding/json (v1 semantics: nil slices and maps encode as null, case-insensitive field matching, duplicate object names tolerated). Its wire format is unchanged from earlier releases, so caches written by older binaries stay readable.
type JSONV2Codec ¶ added in v0.4.0
type JSONV2Codec struct{}
JSONV2Codec encodes values via encoding/json/v2 with its stricter defaults: nil slices and maps encode as [] and {}, field names match case-sensitively, and duplicate object names and invalid UTF-8 are rejected on decode. Use it for new caches; switching an existing cache from JSONCodec changes the stored representation of nil containers.
type KeyCodec ¶ added in v0.3.0
KeyCodec encodes a key into the Redis key string. A Cache owns one KeyCodec and may use it with different key types across operations; implementations must be concurrent-safe and return an error for unsupported key types. StringKeyCodec is the default; KeyCodecFunc adapts a typed function.
type KeyCodecFunc ¶ added in v0.3.0
KeyCodecFunc adapts a typed function into a KeyCodec. Keys of any type other than K are rejected with an error.
type Logger ¶ added in v0.1.6
Logger is the slog-shaped subset the cache calls into. *slog.Logger satisfies it.
type MemoryOption ¶ added in v0.4.0
type MemoryOption func(*memEngine)
MemoryOption configures OpenMemory.
func WithMemoryClock ¶ added in v0.4.0
func WithMemoryClock(now func() time.Time) MemoryOption
WithMemoryClock sets the time source used for TTL expiry, so tests can advance time without sleeping. The default is time.Now.
type Metrics ¶ added in v0.1.7
type Metrics interface {
CacheHits(n int64)
CacheMisses(n int64)
LockContended(n int64)
// LockWaitDuration fires once per resolved wait, regardless of outcome
// (invalidation, ctx cancel, or lockTTL). Typically histogrammed.
LockWaitDuration(d time.Duration)
// LoaderDuration measures foreground origin-loader latency (Get/GetMulti
// miss, Set/SetMulti). Background refresh is excluded. Typically histogrammed.
LoaderDuration(d time.Duration)
// LoaderErrors fires when a foreground loader returns an error; n is the
// number of keys the loader was responsible for (1 for single, len(missing)
// for multi).
LoaderErrors(n int64)
// RedisError records command failures with op "read", "lock", "set",
// "del", or "touch". "read_fallback" counts an attempted uncached retry
// after a clustered cached read aborted. It emits one event per uncached
// retry attempt, whether for one key or a batch. A polling Get or
// GetMulti can make more than one attempt. The count includes retries
// that fail, return Redis nil, or are canceled before sending. Missing
// PTTL permission can trigger an abort. A sustained rate alone cannot
// identify a server-side EXEC abort because rueidis also reports
// ErrDoCacheAborted when a connection closes.
// Lock-lost, Redis nil, and script-drift parse failures are excluded
// from the command-failure labels.
RedisError(op string)
RefreshTriggered(n int64)
// RefreshSkipped covers both local and distributed dedup.
RefreshSkipped(n int64)
// RefreshDropped fires when the refresh queue is full.
RefreshDropped(n int64)
// LockLost fires when a CAS detected a stolen lock (e.g. via ForceSet).
LockLost(key string)
RefreshError(key string)
// RefreshPanicked fires once per key when a refresh callback panicked.
RefreshPanicked(key string)
// InvalidationError fires when an invalidation message couldn't be parsed.
InvalidationError()
}
Metrics receives observability events. Methods run on the hot path and must be concurrent-safe. High-volume events (hits/misses/contention/refresh counts) are batched per operation and emitted once with n. Diagnostics (LockLost, RefreshError, RefreshPanicked) carry the affected key. Embed NoopMetrics to opt in to a subset.
type NoopMetrics ¶ added in v0.1.7
type NoopMetrics struct{}
NoopMetrics is the zero-value Metrics implementation. Embed and override.
Example ¶
Pass a Metrics implementation via WithMetrics to count cache events. The cache calls these on the hot path, batched per operation. This example invokes them directly (no Redis needed) to show the counting shape.
package main
import (
"fmt"
"sync/atomic"
"github.com/dcbickfo/redcache"
)
// countingMetrics shows the embed-and-override pattern: embed NoopMetrics and
// implement only the events you care about.
type countingMetrics struct {
redcache.NoopMetrics
hits, misses atomic.Int64
}
func (m *countingMetrics) CacheHits(n int64) { m.hits.Add(n) }
func (m *countingMetrics) CacheMisses(n int64) { m.misses.Add(n) }
func main() {
m := &countingMetrics{}
// In real use: open a Conn and construct redcache.New(conn, codec) with redcache.WithMetrics(m) passed to Open.
m.CacheHits(3)
m.CacheMisses(1)
fmt.Println(m.hits.Load(), m.misses.Load())
}
Output: 3 1
func (NoopMetrics) CacheHits ¶ added in v0.2.0
func (NoopMetrics) CacheHits(int64)
func (NoopMetrics) CacheMisses ¶ added in v0.2.0
func (NoopMetrics) CacheMisses(int64)
func (NoopMetrics) InvalidationError ¶ added in v0.1.7
func (NoopMetrics) InvalidationError()
func (NoopMetrics) LoaderDuration ¶ added in v0.3.0
func (NoopMetrics) LoaderDuration(time.Duration)
func (NoopMetrics) LoaderErrors ¶ added in v0.3.0
func (NoopMetrics) LoaderErrors(int64)
func (NoopMetrics) LockContended ¶ added in v0.1.7
func (NoopMetrics) LockContended(int64)
func (NoopMetrics) LockLost ¶ added in v0.1.7
func (NoopMetrics) LockLost(string)
func (NoopMetrics) LockWaitDuration ¶ added in v0.2.0
func (NoopMetrics) LockWaitDuration(time.Duration)
func (NoopMetrics) RedisError ¶ added in v0.3.0
func (NoopMetrics) RedisError(string)
func (NoopMetrics) RefreshDropped ¶ added in v0.1.7
func (NoopMetrics) RefreshDropped(int64)
func (NoopMetrics) RefreshError ¶ added in v0.1.7
func (NoopMetrics) RefreshError(string)
func (NoopMetrics) RefreshPanicked ¶ added in v0.1.7
func (NoopMetrics) RefreshPanicked(string)
func (NoopMetrics) RefreshSkipped ¶ added in v0.1.7
func (NoopMetrics) RefreshSkipped(int64)
func (NoopMetrics) RefreshTriggered ¶ added in v0.1.7
func (NoopMetrics) RefreshTriggered(int64)
type Option ¶ added in v0.3.0
type Option func(*config)
Option configures a Conn. Options are applied in order; later wins.
func WithClientBuilder ¶ added in v0.3.0
WithClientBuilder overrides rueidis.NewClient when building the internal client. Useful as a test seam.
func WithLockPrefix ¶ added in v0.3.0
WithLockPrefix sets the in-Redis prefix tagged onto lock values so reads can recognise a lock as a miss. Defaults to DefaultLockPrefix.
func WithLockTTL ¶ added in v0.3.0
WithLockTTL bounds both how long a Redis lock survives and how long callers wait for one. Defaults to 10s; values below 100ms are rejected.
func WithLogger ¶ added in v0.3.0
WithLogger sets the logger. Defaults to slog.Default().
func WithMetrics ¶ added in v0.3.0
WithMetrics sets the metrics sink. Defaults to NoopMetrics. Methods run on the hot path; impls must be concurrent-safe.
func WithRefreshAfterFraction ¶ added in v0.3.0
WithRefreshAfterFraction enables refresh-ahead. Reads with remaining TTL below (1 - fraction) * ttl may trigger a background refresh while still returning the cached value. Must be in [0, 1); 0 disables.
func WithRefreshBeta ¶ added in v0.3.0
WithRefreshBeta enables XFetch-style probabilistic sampling within the refresh window, weighting by recorded compute time so slow values get more headroom. 0 (default) = always refresh below the floor; 1.0 matches canonical XFetch (Vattani et al). Multi-key writes record fn duration divided evenly across returned values.
func WithRefreshLockPrefix ¶ added in v0.3.0
WithRefreshLockPrefix sets the prefix for refresh-ahead dedup keys. Defaults to DefaultRefreshPrefix. Refresh lock keys embed the data key for uniqueness; refresh-ahead correctness does not require Redis cluster-slot co-location.
func WithRefreshQueueSize ¶ added in v0.3.0
WithRefreshQueueSize bounds pending refresh jobs; over-full drops are counted via RefreshDropped. Defaults to 64.
func WithRefreshTimeout ¶ added in v0.3.0
WithRefreshTimeout bounds how long a refresh-ahead callback may run. Defaults to the data ttl passed to Get/GetMulti (not LockTTL). The refresh lock itself still uses LockTTL; the back-write that records a slow-but-successful result is decoupled from this timeout so it is not lost.
func WithRefreshWorkers ¶ added in v0.3.0
WithRefreshWorkers sets the refresh worker pool size. Defaults to 4.
type StringCodec ¶ added in v0.3.0
type StringCodec struct{}
StringCodec is the identity codec for string.
type StringKeyCodec ¶ added in v0.3.0
type StringKeyCodec struct{}
StringKeyCodec is the default KeyCodec. A string, or any type whose underlying type is string, is used as-is (this is what enables the zero-allocation multi-key fast path); an encoding.TextMarshaler is encoded with MarshalText; any other type is an error.
type UnsafeBytesCodec ¶ added in v0.3.0
type UnsafeBytesCodec struct{}
UnsafeBytesCodec is the zero-copy identity codec for []byte. It aliases library-internal memory in both directions: Encode hands its input straight to the library (which may alias it), and Decode returns a []byte backed by the cache's borrowed read buffer. The decoded slice must not be mutated or retained past the call. Use a copying codec if you need an owned value.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
metrics
command
Package main demonstrates wiring a custom Metrics implementation.
|
Package main demonstrates wiring a custom Metrics implementation. |
|
string-cache
command
Package main demonstrates a migration-friendly string-key/string-value cache.
|
Package main demonstrates a migration-friendly string-key/string-value cache. |
|
typed-cache
command
Package main demonstrates typed keys and JSON-encoded values.
|
Package main demonstrates typed keys and JSON-encoded values. |
|
internal
|
|
|
lockpool
Package lockpool provides fast lock value generation using an atomic counter and a per-instance UUID prefix.
|
Package lockpool provides fast lock value generation using an atomic counter and a per-instance UUID prefix. |
|
poolx
Package poolx provides typed sync.Pool wrappers for reusing slice headers across multi-key call paths.
|
Package poolx provides typed sync.Pool wrappers for reusing slice headers across multi-key call paths. |
|
syncx
Package syncx provides concurrency helpers: a sharded string-keyed map and a multi-channel wait.
|
Package syncx provides concurrency helpers: a sharded string-keyed map and a multi-channel wait. |
|
Package redcacheotel provides a drop-in OpenTelemetry adapter for the redcache.Metrics interface.
|
Package redcacheotel provides a drop-in OpenTelemetry adapter for the redcache.Metrics interface. |