cache

package
v0.40.416 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 13 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cache provides a small key/value cache abstraction (Provider) with a TTL per entry, a pattern-based key listing and a minimal publish/subscribe channel, backed either by process memory or by Redis.

Values are JSON encoded on Set and decoded into the pointer passed to Get, so both backends behave the same. A missing or expired entry is reported as ErrNotFound (test with IsNotFoundError). Keys are joined with the provider prefix using path.Join.

var p cache.Provider
if cfg.Provider == "redis" {
	p, err = cache.NewRedisProvider(*cfg.Redis, "/myapp")
} else {
	p = cache.NewMemoryProvider("/myapp")
}
err = p.Set(ctx, "user:1", user, 10*time.Minute) // 0 => default TTL, cache.KeepTTL => no expiry
var u User
err = p.Get(ctx, "user:1", &u)

// scope a shared provider to a sub-namespace
users := cache.NewProxyProvider("users", p)

Config YAML/JSON fields: provider (redis|memory) and redis {server, ttl, client_tls {cert, key, trusted_ca}, user, password}. The package does not itself switch on Config.Provider; the caller picks the constructor.

TTL: a ttl of 0 means DefaultTTL for the memory provider and RedisConfig.TTL (default 1h) for Redis; KeepTTL stores the value without expiry (Redis KEEPTTL). The memory provider never evicts on its own: the caller must run CleanExpired periodically, and NowFunc can be overridden in tests to control its clock.

Pub/Sub: Subscribe returns a Subscription whose ReceiveMessage blocks until a message arrives or the context is done (checked about once a second); Close unregisters it. The memory provider delivers to every subscriber of the channel in-process only; the Redis provider uses Redis channels, which are not prefixed.

Index

Constants

This section is empty.

Variables

View Source
var DefaultTTL = 30 * time.Minute

DefaultTTL is the expiry applied by the memory provider when Set is called with ttl == 0. It is a package variable and may be changed at startup.

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned by Get for a missing or expired key.

View Source
var KeepTTL = time.Duration(-1)

KeepTTL is the ttl value for Set that stores the value without expiry (Redis KEEPTTL semantics: an existing key keeps its TTL, a new key has none).

View Source
var NowFunc = time.Now

NowFunc is the clock used by the memory provider for expiry; override it in tests to simulate time passing.

Functions

func GetOrSet added in v0.24.557

func GetOrSet(ctx context.Context, p Provider, key string, value any, getter func() (any, error)) error

GetOrSet decodes the cached value for key into value (a non-nil pointer). On a miss it calls getter, which must return a pointer, and copies the pointed-to result into value. Note that the result is NOT written back to the cache; callers must Set it themselves. Errors other than a miss are returned as-is.

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError reports whether err is (or wraps) ErrNotFound, or whose message contains "not found".

Types

type Config

type Config struct {
	// Provider specifies the cache provider: redis|memory
	Provider string `json:"provider" yaml:"provider"`
	// Redis holds the Redis connection settings when Provider is "redis".
	Redis *RedisConfig `json:"redis" yaml:"redis"`
}

Config specifies configuration of the cache. The package does not switch on Provider itself; callers choose NewMemoryProvider or NewRedisProvider(*Config.Redis, prefix).

type Provider

type Provider interface {
	// Set stores v (JSON encoded, or raw for string/[]byte on Redis) under
	// key. ttl == 0 applies the provider default, KeepTTL disables expiry.
	Set(ctx context.Context, key string, v any, ttl time.Duration) error
	// Get decodes the value stored under key into v, which must be a
	// non-nil pointer. It returns ErrNotFound for a missing or expired key.
	Get(ctx context.Context, key string, v any) error
	// Delete removes the keys; missing keys are not an error.
	Delete(ctx context.Context, keys ...string) error
	// CleanExpired removes expired entries from the memory provider;
	// it is a no-op for Redis, which expires keys itself.
	CleanExpired(ctx context.Context)
	// Close closes the client, releasing any open resources.
	// It is rare to Close a Client, as the Client is meant to be long-lived and shared between many goroutines.
	Close() error
	// Keys returns the keys matching pattern (glob for Redis, prefix match
	// for memory). It scans the whole keyspace and is meant for tests.
	Keys(ctx context.Context, pattern string) ([]string, error)

	// IsLocal returns true when the cache lives in this process only.
	IsLocal() bool

	// Publish sends message to every subscriber of channel.
	Publish(ctx context.Context, channel, message string) error
	// Subscribe registers a subscriber for channel; call Close on the result
	// when done.
	Subscribe(ctx context.Context, channel string) Subscription
}

Provider is the cache interface implemented by the memory, Redis and proxy providers. Implementations are safe for concurrent use.

func NewMemoryProvider

func NewMemoryProvider(prefix string) Provider

NewMemoryProvider returns an in-process Provider whose keys are joined with prefix. Values are kept JSON encoded; the store is unbounded and expired entries are only dropped on Get or CleanExpired.

func NewProxyProvider

func NewProxyProvider(prefix string, prov Provider) Provider

NewProxyProvider returns a Provider that prefixes every key with prefix and delegates to prov. Its Close is a no-op (the parent owns the connection) and Publish/Subscribe pass channels through unprefixed.

func NewRedisProvider

func NewRedisProvider(cfg RedisConfig, prefix string) (Provider, error)

NewRedisProvider returns a Provider backed by Redis. cfg.Server is parsed with redis.ParseURL; cfg.ClientTLS files (if set) configure TLS and cfg.Password overrides the URL credentials. An empty prefix becomes "/"; a zero cfg.TTL becomes 1h. Maintenance notifications are disabled. The connection is established lazily, so a bad address only fails later.

type RedisConfig

type RedisConfig struct {
	// Server is the redis:// or rediss:// URL.
	Server string `json:"server,omitempty" yaml:"server,omitempty"`
	// TTL is the expiry applied when Set is called with ttl == 0; default 1h.
	TTL time.Duration `json:"ttl,omitempty" yaml:"ttl,omitempty"`
	// ClientTLS describes the TLS certs used to connect to the cluster
	ClientTLS *gserver.TLSInfo `json:"client_tls,omitempty" yaml:"client_tls,omitempty"`
	// User is the ACL user name; only applied when Password is set.
	User string `json:"user,omitempty" yaml:"user,omitempty"`
	// Password overrides the credentials embedded in Server.
	Password string `json:"password,omitempty" yaml:"password,omitempty"`
}

RedisConfig specifies the Redis connection used by NewRedisProvider.

type Subscription

type Subscription interface {
	// Close unregisters the subscription and releases its resources.
	Close() error
	// ReceiveMessage blocks until a message arrives or ctx is done
	// (checked about once per second), returning ctx.Err() in the latter case.
	ReceiveMessage(ctx context.Context) (string, error)
}

Subscription is a channel subscription returned by Provider.Subscribe.

Jump to

Keyboard shortcuts

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