Skip to content
omeyang edited this page Sep 17, 2026 · 1 revision

pkg/storage/xcache

稳定性:Stable · 覆盖率:93.8% · 源码:pkg/storage/xcache

缓存抽象层。Redis / Memory 双后端 + Cache-Aside 助手。

用途

  • 业务代码不写 Redis client 直接调用
  • 测试时切换 Memory 后端
  • 标准 Cache-Aside 流程

快速上手

import "github.com/omeyang/xkit/pkg/storage/xcache"

c := xcache.NewRedis(redisClient, "myapp")

// Cache-Aside
val, err := xcache.GetOrLoad(ctx, c, "user:123",
    5*time.Minute,
    func(ctx context.Context) (*User, error) {
        return loadFromDB(ctx, "123")
    },
)

关键类型与函数

名称 说明
Cache interface Get / Set / Del / GetMulti / SetMulti
NewRedis(client, namespace) Cache Redis 后端
NewMemory(maxEntries, ttl) Cache 内存后端(基于 xlru)
GetOrLoad[T](ctx, c, key, ttl, loader) Cache-Aside 助手

设计要点

  • 接口由使用方定义:业务方可写自家 mock
  • namespace 前缀:避免多服务同 Redis 撞 key

相关

Clone this wiki locally