ling-baseling-base

Cache 缓存

统一缓存接口,LRU、Redis、多级缓存等后端

在线 Playground

在浏览器中直接体验本页相关 API,无需本地安装 Go 环境。

另见专题文档:缓存完整文档。以下为 common/cache 包 README 全文。

Cache

Unified caching for ling-base.

On-demand modules

Module pathThird-party deps
github.com/LingByte/ling-base/common/cachenone (interface + lru/memory/noop/multilevel)
.../cache/bigcacheallegro/bigcache
.../cache/redisgo-redis
.../cache/memcachegomemcache
.../cache/freecachefreecache
.../cache/ristrettoristretto
go get github.com/LingByte/ling-base/common/cache              # 纯标准库
go get github.com/LingByte/ling-base/common/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

PackageDescription
cache/lruThread-safe LRU with optional TTL and background cleanup
cache/memorySimple concurrent map cache with TTL
cache/noopNo-op implementation
cache/multilevelComposes two cache.Cache instances (L1 + L2)
cache/freecacheFreeCache
cache/bigcacheBigCache — global LifeWindow only
cache/ristrettoRistretto
cache/memcacheMemcached via gomemcache
cache/redisRedis via go-redis

Quick start

LRU

import (
    "context"
    "time"

    "github.com/LingByte/ling-base/common/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/common/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/common/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).

On this page