cache

package
v1.23.8 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 5 Imported by: 6

README

cache

带本地 TinyLFU 的 对象缓存(基于 go-redis/cache),适用于 token 校验等需要「Redis + 进程内缓存」的场景。

裸 Redis 命令(KV、List、Pub/Sub 等)见 redis/README.md

与 redis 的关系

用途 业务入口
redis 共享 Redis 连接,全命令集 app.GetRedisClient()
cache 本地 LFU + Redis 对象缓存 app.GetCache()

初始化有依赖: 必须先 EnableRedis,再 EnableCache(共用同一 redis.Client)。

builder.
    EnableRedis(redis.Options{
        Addr:     addr,
        Password: pwd,
    }).
    EnableCache(cache.Options{
        MaxSize: 10000,
        Ttl:     time.Minute,
    })

仅 Redis、不需要本地 cache 时,只调用 EnableRedis 即可,不必 EnableCache

使用

c := app.GetCache()

var obj MyStruct
err := c.Get("key", &obj)
if cache.IsNotFound(err) {
    // key 不存在
}

_ = c.Set("key", &obj)
_ = c.SetTTL("key", &obj, time.Hour)
_ = c.Del("key")
ok := c.Exists("key")

GetSkipLocal 跳过本地 LFU,直接读 Redis。

错误处理

cache.CGet / Set / Del 出口调用 NormalizeErr,返回 cache.ErrNotFound,不是原始 redis.Nil

函数 说明
cache.IsNotFound(err) cache.C 返回的 err(已归一化)
cache.IsNotFoundAny(err) 兼容原始 redis.Nil 或归一化 err

业务不要 import "github.com/redis/go-redis/v9"
使用 app.GetRedisClient() 时的 err 判断见 redis.IsRedisNil

err := app.GetCache().Get(key, &obj)
if cache.IsNotFound(err) {
    // missing key
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errNotFound

ErrNotFound is returned by cache.C APIs after NormalizeErr (not redis.Nil).

Functions

func IsNotFound added in v1.22.7

func IsNotFound(err error) bool

IsNotFound reports normalized not-found errors from cache.C.

func IsNotFoundAny added in v1.22.8

func IsNotFoundAny(err error) bool

IsNotFoundAny reports not-found for raw redis.Nil or normalized cache errors.

func NormalizeErr added in v1.22.7

func NormalizeErr(err error) error

NormalizeErr maps redis driver errors to cache-level errors.

Types

type C

type C interface {
	Get(key string, value interface{}) (err error)
	GetSkipLocal(key string, value interface{}) (err error)
	GetProxy() *cache.Cache
	Exists(key string) bool
	Set(key string, value interface{}) (err error)
	SetTTL(key string, value interface{}, ttl time.Duration) (err error)
	Del(key string) error
}

func New

func New(ctx context.Context, client *starterredis.Client, cacheOpts Options) (c C)

New builds a cache.C from an existing redis.Client (shared with app.GetRedisClient).

type Options

type Options struct {
	MaxSize int
	Ttl     time.Duration
}

Jump to

Keyboard shortcuts

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