cache

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 4 Imported by: 0

README

Cache

Unified caching for ling-base.

On-demand modules

Module path Third-party deps
github.com/LingByte/ling-base/cache none (interface + lru/memory/noop/multilevel)
.../cache/bigcache allegro/bigcache
.../cache/redis go-redis
.../cache/memcache gomemcache
.../cache/freecache freecache
.../cache/ristretto ristretto
go get github.com/LingByte/ling-base/cache              # 纯标准库
go get github.com/LingByte/ling-base/cache/bigcache     # 仅拉 bigcache

Features

  • Common cache.Cache interface
  • In-memory LRU / memory / noop / multilevel
  • freecache, bigcache, ristretto, Memcached, Redis adapters
  • Helpers: GetString / SetString / GetJSON / SetJSON / GetOrSet

Backends

Package Description
cache/lru Thread-safe LRU with optional TTL and background cleanup
cache/memory Simple concurrent map cache with TTL
cache/noop No-op implementation
cache/multilevel Composes two cache.Cache instances (L1 + L2)
cache/freecache FreeCache
cache/bigcache BigCache — global LifeWindow only
cache/ristretto Ristretto
cache/memcache Memcached via gomemcache
cache/redis Redis via go-redis

Quick start

LRU
import (
    "context"
    "time"

    "github.com/LingByte/ling-base/cache/lru"
)

c, err := lru.New(1024,
    lru.WithPrefix("app:"),
    lru.WithDefaultTTL(5*time.Minute),
)
if err != nil {
    panic(err)
}
defer c.Close()

ctx := context.Background()
_ = c.Set(ctx, "user:1", []byte(`{"id":1}`), 0)
val, err := c.Get(ctx, "user:1")
_ = val
BigCache
import (
    "time"
    cachebig "github.com/LingByte/ling-base/cache/bigcache"
)

// LifeWindow is the only TTL mechanism. Optional WithStrictTTL rejects per-key ttl.
c, err := cachebig.New(10*time.Minute, cachebig.WithStrictTTL())
Redis
import (
    "github.com/redis/go-redis/v9"
    cacheredis "github.com/LingByte/ling-base/cache/redis"
)

c, err := cacheredis.New(&redis.Options{Addr: "127.0.0.1:6379"},
    cacheredis.WithPrefix("app:"),
)

Interface

type Cache interface {
    Get(ctx context.Context, key string) ([]byte, error)
    Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
    Delete(ctx context.Context, key string) error
    Exists(ctx context.Context, key string) (bool, error)
    Clear(ctx context.Context) error
    Close() error
}

ttl == 0 means no expiration unless WithDefaultTTL is set (backend permitting).

Documentation

Overview

Package cache defines a unified generic caching interface and shared errors for in-memory and distributed cache backends.

The Cache[K, V] interface is generic over key and value types. In-memory backends (lru, memory, ristretto) can use arbitrary types; distributed backends (redis, memcache, bigcache, freecache) typically use Cache[string, []byte].

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when a key does not exist or has expired.
	ErrNotFound = errors.New("cache: key not found")

	// ErrClosed is returned when an operation is attempted on a closed cache.
	ErrClosed = errors.New("cache: closed")

	// ErrInvalidCapacity is returned when capacity is less than or equal to zero.
	ErrInvalidCapacity = errors.New("cache: capacity must be greater than zero")

	// ErrEmptyKey is returned when a key is empty.
	ErrEmptyKey = errors.New("cache: key must not be empty")
)

Functions

func GetJSON

func GetJSON(ctx context.Context, c ByteCache, key string, dest any) error

GetJSON unmarshals a cached JSON value into dest.

func GetOrSet

func GetOrSet(ctx context.Context, c ByteCache, key string, ttl time.Duration, fn func(context.Context) ([]byte, error)) ([]byte, error)

GetOrSet returns the cached value for key, or calls fn to produce and store it.

func GetString

func GetString(ctx context.Context, c ByteCache, key string) (string, error)

GetString is a convenience wrapper around ByteCache.Get.

func SetJSON

func SetJSON(ctx context.Context, c ByteCache, key string, value any, ttl time.Duration) error

SetJSON marshals value as JSON and stores it.

func SetString

func SetString(ctx context.Context, c ByteCache, key, value string, ttl time.Duration) error

SetString is a convenience wrapper around ByteCache.Set.

Types

type ByteCache

type ByteCache = Cache[string, []byte]

ByteCache is a type alias for the common distributed-cache specialization: string keys and []byte values.

type Cache

type Cache[K comparable, V any] interface {
	// Get returns the value for key. Returns ErrNotFound if missing or expired.
	Get(ctx context.Context, key K) (V, error)

	// Set stores value under key. A ttl of 0 means no expiration (backend permitting).
	Set(ctx context.Context, key K, value V, ttl time.Duration) error

	// Delete removes key. It is not an error if the key does not exist.
	Delete(ctx context.Context, key K) error

	// Exists reports whether key is present and not expired.
	Exists(ctx context.Context, key K) (bool, error)

	// Clear removes all entries from the cache.
	Clear(ctx context.Context) error

	// Close releases resources held by the cache.
	Close() error
}

Cache is the common generic interface implemented by all cache backends.

In-memory backends can use arbitrary K and V types; distributed backends typically use Cache[string, []byte].

type Getter

type Getter[K comparable, V any] interface {
	Get(ctx context.Context, key K) (V, error)
	Exists(ctx context.Context, key K) (bool, error)
}

Getter is a read-only view of a cache.

type Option

type Option func(*Options)

Option mutates Options.

func WithDefaultTTL

func WithDefaultTTL(ttl time.Duration) Option

WithDefaultTTL sets the default TTL used when Set is called with ttl == 0.

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix sets a key prefix.

type Options

type Options struct {
	// Prefix is prepended to every key before it is sent to the backend.
	Prefix string

	// DefaultTTL is applied by Set when the caller passes ttl == 0 and the
	// backend supports expiration. A zero DefaultTTL means "no expiration".
	DefaultTTL time.Duration
}

Options holds shared configuration knobs used by cache backends.

func ApplyOptions

func ApplyOptions(opts ...Option) Options

ApplyOptions builds Options from the given Option list.

func (Options) Key

func (o Options) Key(key string) string

Key prefixes key with Prefix when Prefix is non-empty.

func (Options) ResolveTTL

func (o Options) ResolveTTL(ttl time.Duration) time.Duration

ResolveTTL returns ttl if positive, otherwise DefaultTTL.

type Setter

type Setter[K comparable, V any] interface {
	Set(ctx context.Context, key K, value V, ttl time.Duration) error
	Delete(ctx context.Context, key K) error
}

Setter is a write-only view of a cache.

Directories

Path Synopsis
Package lru provides a generic in-memory LRU cache with optional TTL (expiration).
Package lru provides a generic in-memory LRU cache with optional TTL (expiration).
Package memory provides a simple concurrent in-memory cache with TTL.
Package memory provides a simple concurrent in-memory cache with TTL.
Package multilevel composes an L1 (local) and L2 (remote) cache.
Package multilevel composes an L1 (local) and L2 (remote) cache.
Package noop provides a no-op cache useful for tests and feature flags.
Package noop provides a no-op cache useful for tests and feature flags.

Jump to

Keyboard shortcuts

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