cache

package module
v0.33.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 22, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package cache provides a small key/value cache abstraction with a Redis-backed implementation (for cross-replica sharing) and an in-memory implementation (for single-instance or tests). It lives in its own module so the Redis dependency is not forced on services that do not need it.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetJSON

func GetJSON[T any](ctx context.Context, c Cache, key string) (T, bool, error)

GetJSON fetches key and JSON-decodes it into T. found is false (with a zero T and nil error) when the key is absent.

func Module added in v0.19.0

func Module(name ...string) host.Module

Module registers a cache service that loads its config from cache and connects at Init time. Driver "memory" (default) or "redis". The connection is closed automatically on shutdown.

host.MustNew().WithModule(cache.Module()).MustRun()

Pass an optional name to install several caches side by side; a named cache reads its own [cache.<name>] config section and is retrieved with cache.Of(app, name). Reach the default cache with cache.Of(app).

func ModuleWithClient added in v0.19.0

func ModuleWithClient(c Cache, name ...string) host.Module

ModuleWithClient registers a pre-built Cache (e.g. a MemoryCache in tests or a custom implementation), bypassing config loading and Init. It is still closed by the lifecycle on shutdown. Pass an optional name to register it as a named instance.

func SetJSON

func SetJSON[T any](ctx context.Context, c Cache, key string, v T, ttl time.Duration) error

SetJSON JSON-encodes v and stores it under key with the given ttl.

Types

type Cache

type Cache interface {
	GetBytes(ctx context.Context, key string) (value []byte, found bool, err error)
	SetBytes(ctx context.Context, key string, value []byte, ttl time.Duration) error
	Get(ctx context.Context, key string) (value any, found bool, err error)
	Set(ctx context.Context, key string, value any, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
	Close() error
}

Cache is a byte-oriented key/value store with per-entry expiry. A zero ttl means no expiry. Get reports found=false for a missing or expired key.

func Lookup added in v0.23.0

func Lookup(app *host.App, name ...string) (Cache, bool)

Lookup returns the cache installed under the optional name and whether one was installed. Use it where absence is an expected, recoverable condition; prefer Of when the cache must exist.

func New added in v0.4.0

func New(ctx context.Context, cfg Config, timeProvider core.TimeProvider) (Cache, error)

New builds a Cache from cfg. An empty or "memory" driver returns an in-process MemoryCache; "redis" connects to Redis (verifying the connection with a PING).

func Of added in v0.19.0

func Of(app *host.App, name ...string) Cache

Of returns the cache installed by Module/ModuleWithClient under the optional name, panicking if none was installed. It is available after services are initialized.

type Config added in v0.4.0

type Config struct {
	Driver   string `mapstructure:"driver"`
	Addr     string `mapstructure:"addr"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
	Prefix   string `mapstructure:"prefix"`
}

Config selects and configures a Cache. Driver "memory" (the default) needs no other fields; "redis" uses Addr/Password/DB. Prefix is prepended to every key.

type MemoryCache

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache is an in-process Cache with TTL expiry, safe for concurrent use. Suitable for single-instance services and tests; use RedisCache when entries must be shared across replicas.

Get/Set store arbitrary values in the in-process map without serialization, so the exact value (including its concrete type) is returned. GetBytes/SetBytes share the same map; a value stored with one pair is not visible to the other.

func NewMemoryCache

func NewMemoryCache(timeProvider core.TimeProvider) *MemoryCache

NewMemoryCache returns an empty in-memory cache.

func (*MemoryCache) Close

func (m *MemoryCache) Close() error

func (*MemoryCache) Delete

func (m *MemoryCache) Delete(_ context.Context, key string) error

func (*MemoryCache) Get

func (m *MemoryCache) Get(_ context.Context, key string) (any, bool, error)

Get returns the value stored for key. The value is returned as-is, with its original concrete type, so callers type-assert it back.

func (*MemoryCache) GetBytes added in v0.16.0

func (m *MemoryCache) GetBytes(_ context.Context, key string) ([]byte, bool, error)

func (*MemoryCache) Set

func (m *MemoryCache) Set(_ context.Context, key string, value any, ttl time.Duration) error

Set stores value for key. The value is held directly in the in-process map, not copied or serialized, so callers must not mutate it after storing.

func (*MemoryCache) SetBytes added in v0.16.0

func (m *MemoryCache) SetBytes(_ context.Context, key string, value []byte, ttl time.Duration) error

type RedisCache

type RedisCache struct {
	// contains filtered or unexported fields
}

RedisCache is a Redis-backed Cache, suitable for sharing entries across replicas. Keys are optionally namespaced with a prefix.

func NewRedis

func NewRedis(ctx context.Context, opts RedisOptions) (*RedisCache, error)

NewRedis connects to Redis and verifies the connection with a PING.

func NewRedisWithClient

func NewRedisWithClient(client *redis.Client, prefix string) *RedisCache

NewRedisWithClient wraps an existing *redis.Client (for shared clients or custom configuration).

func (*RedisCache) Close

func (r *RedisCache) Close() error

func (*RedisCache) Delete

func (r *RedisCache) Delete(ctx context.Context, key string) error

func (*RedisCache) Get

func (r *RedisCache) Get(ctx context.Context, key string) (any, bool, error)

Get fetches key and gob-decodes the stored value. Because Redis cannot hold live Go values, Set serializes with encoding/gob; the dynamic type of the value must be registered with gob.Register for the decode to reconstruct it.

func (*RedisCache) GetBytes added in v0.16.0

func (r *RedisCache) GetBytes(ctx context.Context, key string) ([]byte, bool, error)

func (*RedisCache) Healthy

func (r *RedisCache) Healthy(ctx context.Context) error

Healthy reports an error when Redis does not respond to a PING. It lets a RedisCache double as a host readiness probe.

func (*RedisCache) Set

func (r *RedisCache) Set(ctx context.Context, key string, value any, ttl time.Duration) error

Set gob-encodes value and stores it under key with the given ttl. The dynamic type of value must be registered with gob.Register so Get can decode it back into the same type.

func (*RedisCache) SetBytes added in v0.16.0

func (r *RedisCache) SetBytes(ctx context.Context, key string, value []byte, ttl time.Duration) error

type RedisOptions

type RedisOptions struct {
	// Addr is the Redis address, e.g. "localhost:6379".
	Addr string
	// Password and DB are optional.
	Password string
	DB       int
	// Prefix is prepended to every key (e.g. "myservice:").
	Prefix string
}

RedisOptions configures a RedisCache.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL