Documentation
¶
Overview ¶
Package cache provides cache abstractions, configuration, and drivers for go-service.
The primary entrypoint is NewCache, which constructs a *Cache from configuration.
Disabled / nil behavior ¶
Caching is intentionally optional. When cache configuration is disabled/unset, constructors return nil and callers are expected to tolerate a nil cache instance.
In addition to the instance API on *Cache, this package exposes package-level generic helpers (Get, Persist, and GetOrPersist). Those helpers are nil-safe after Register has been called (via DI wiring in Module). When caching is disabled, Persist is a no-op, Get returns nil, false, nil, and GetOrPersist returns a nil value without calling its loader. In the standard service composition this registration is performed for you by the module graph.
Value encoding ¶
Cache persists arbitrary values by encoding (and optionally compressing) them before passing them to the configured driver. The encoder/compressor used is selected by configuration with sensible defaults. The configured encoder and compressor are also included in the driver key namespace so format changes create cache misses instead of decoding values written by an incompatible format.
Redis compatibility ¶
Atomic publication through Cache.GetOrPersist and the package-level GetOrPersist helper requires Redis 7.0-compatible `SET` semantics when the built-in Redis driver is selected. The driver publishes with `SET ... NX GET` so concurrent writers converge on the stored winner.
TTL resolution ¶
TTL handling depends on the selected driver. The built-in in-memory "ttlcache" driver stores a bounded number of values in process memory, expires entries when they are read, and removes expired entries before saving new values.
Flush behavior ¶
Cache.Flush delegates to the selected driver and can have backend-wide effects. The built-in Redis backend uses Redis FLUSHDB, so it clears the entire selected Redis database, including keys that were not created through this cache facade. Use a dedicated Redis database for go-service cache data before calling Flush against Redis.
Index ¶
- Variables
- func Get[T any](ctx context.Context, key string) (*T, bool, error)
- func GetOrPersist[T any](ctx context.Context, key string, ttl time.Duration, fn func() (T, error)) (*T, error)
- func Persist[T any](ctx context.Context, key string, value *T, ttl time.Duration) error
- func Register(c *Cache)
- type Cache
- func (c *Cache) Flush(ctx context.Context) error
- func (c *Cache) Get(ctx context.Context, key string, value any) (bool, error)
- func (c *Cache) GetOrPersist(ctx context.Context, key string, value any, ttl time.Duration, fn func() error) error
- func (c *Cache) Persist(ctx context.Context, key string, value any, ttl time.Duration) error
- func (c *Cache) Remove(ctx context.Context, key string) error
- type CacheParams
- type Pinger
Constants ¶
This section is empty.
Variables ¶
var Module = di.Module( di.Constructor(driver.NewDriver), di.Constructor(NewPinger), di.Constructor(NewCache), di.Register(Register), )
Module wires the cache subsystem into go.uber.org/fx.
It provides, in order:
- a cache driver.Driver (see driver.NewDriver)
- an optional cache Pinger for backends that support connectivity checks
- a *Cache (see NewCache)
- package-level registration (see Register) so generic helpers (Get/Persist) can be used
Disabled behavior ¶
When caching is disabled via configuration, driver.NewDriver returns a nil driver.Driver and NewCache returns a nil *Cache. Register is still invoked with nil, which makes the package-level helpers behave as if caching is disabled (no-ops / zero values) rather than failing.
Functions ¶
func Get ¶
Get loads a cached value for key into a newly allocated value of type T and reports whether a value was found.
Semantics:
- If caching is disabled (no cache registered), Get returns nil, false, and a nil error.
- If the cache driver reports a miss/expired entry, Get returns a zero-value *T, false, and a nil error.
- If a non-miss error occurs (for example decode failure or driver error), Get returns the zero-value *T, false, along with that error.
func GetOrPersist ¶ added in v2.657.0
func GetOrPersist[T any](ctx context.Context, key string, ttl time.Duration, fn func() (T, error)) (*T, error)
GetOrPersist returns the cached value for key, or produces and stores a new value of type T via fn when the key is absent.
If caching is disabled (no cache registered), GetOrPersist does not call fn and returns a nil value with a nil error, mirroring how Get reports a disabled cache. Callers must tolerate a nil value rather than assuming a value was produced or cached. Concurrent in-process calls for the same key run fn once and share the produced value. With the built-in Redis driver, atomic publication requires Redis 7.0-compatible `SET ... NX GET` semantics.
func Persist ¶
Persist stores value under key with the provided TTL.
If caching is disabled (no cache registered), Persist is a no-op and returns nil. Otherwise it delegates to the registered *Cache.
func Register ¶
func Register(c *Cache)
Register installs the package-level cache instance used by the generic helper functions.
This function is primarily intended to be called by dependency injection wiring (see Module). Once registered, package-level helpers like Get and Persist will delegate to the registered *Cache instance.
If c is nil, the helpers behave as if caching is disabled: Get returns nil, false, nil and Persist is a no-op.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache provides a typed cache facade on top of a cache driver.
It serializes values using an encoder, optionally compresses the serialized bytes, base64-encodes the final bytes, and stores the resulting string via the configured driver.
Encoding selection is operation-dependent:
- Cache.Persist uses "plain" only for io.WriterTo values
- Cache.Get uses "plain" only for io.ReaderFrom destinations
- proto.Message uses "proto"
- otherwise the configured encoder is used, falling back to "json"
Compression is selected from configuration, falling back to "none" when unknown/unavailable.
func NewCache ¶
func NewCache(params CacheParams) *Cache
NewCache constructs a Cache from configuration.
If caching is disabled (i.e. CacheParams.Config is nil), NewCache returns nil. Callers are expected to tolerate a nil cache instance.
func (*Cache) Flush ¶ added in v2.389.0
Flush removes cached data according to the underlying driver's flush semantics.
For persistent backends such as Redis this can be a destructive operation: the built-in Redis driver uses FLUSHDB and clears the entire selected Redis database, including keys that were not created through this cache facade. It is intentionally not called during lifecycle shutdown.
func (*Cache) Get ¶
Get loads a cached value for key into value and reports whether a value was found.
Cache misses are not treated as errors: if the entry is missing or expired, Get returns false, nil and leaves value unchanged.
The value parameter should be a pointer to the destination value (for example *MyStruct).
func (*Cache) GetOrPersist ¶ added in v2.657.0
func (c *Cache) GetOrPersist(ctx context.Context, key string, value any, ttl time.Duration, fn func() error) error
GetOrPersist returns the cached value for key, or produces and stores it via fn when the key is absent.
On a cache hit fn is not called and no write occurs. On a miss fn populates value and the encoded value is published atomically, so concurrent callers converge on a single stored value. Concurrent in-process misses for the same key run fn once and share the produced value; separate processes may each run fn once, but the atomic publish still yields a single stored winner that every caller decodes.
Each concurrent caller waits for the shared fill on its own ctx: if a caller's ctx is canceled or its deadline passes before the fill publishes, that caller returns ctx.Err() instead of blocking until the fill completes. The shared fill runs under the first caller's ctx in a background goroutine and continues even if later callers stop waiting, so a caller that returns early on cancellation must not read value. Because the fill uses the first caller's ctx, canceling that first caller can surface as an error to other callers still waiting on the same fill.
The value parameter should be a pointer to the destination value (for example *MyStruct). It is both populated by fn and used as the decode destination for the resolved value.
With the built-in Redis driver, atomic publication requires Redis 7.0-compatible `SET ... NX GET` semantics.
func (*Cache) Persist ¶
Persist stores value under key with the provided TTL.
The value is encoded, compressed, and base64-encoded before being saved via the driver. A TTL <= 0 is passed through to the driver; semantics are driver-specific (for example, it may mean "no expiration" or "immediate expiration").
TTL resolution is driver-specific.
type CacheParams ¶ added in v2.50.0
type CacheParams struct {
di.In
// Config configures cache encoding, compression, and limits.
Config *config.Config
// Encoder provides value encoders by name.
Encoder *encoding.Map
// Pool provides reusable buffers for cache encoding.
Pool *sync.BufferPool
// Compressor provides compression implementations by name.
Compressor *compress.Map
// Driver stores encoded cache values.
Driver driver.Driver
}
CacheParams defines dependencies for constructing a Cache.
It is intended for dependency injection (go.uber.org/fx/go.uber.org/dig). The constructor will typically be wired via Module.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package config provides cache configuration types for go-service.
|
Package config provides cache configuration types for go-service. |
|
Package driver provides cache driver construction and related helpers for go-service.
|
Package driver provides cache driver construction and related helpers for go-service. |
|
errors
Package errors defines shared sentinel errors and classifiers for cache drivers.
|
Package errors defines shared sentinel errors and classifiers for cache drivers. |
|
internal/redis
Package redis provides the internal Redis cache driver.
|
Package redis provides the internal Redis cache driver. |
|
internal/ttlcache
Package ttlcache provides the internal ttlcache-backed cache driver.
|
Package ttlcache provides the internal ttlcache-backed cache driver. |
|
Package telemetry exposes selected Redis OpenTelemetry helpers through the go-service cache import tree.
|
Package telemetry exposes selected Redis OpenTelemetry helpers through the go-service cache import tree. |