cache

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 7 Imported by: 0 modules, 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 提供基于 Redis 的类型化缓存封装:

  • Get/Set/Delete 使用 JSON 作为统一序列化约定;
  • GetOrSet 基于 singleflight 合并同一进程内的并发加载, 防止缓存击穿(同一个 key 只触发一次回源)。

使用示例:

c := cache.New(db.GetRedis())
var user User
err := cache.GetOrSet(c, ctx, "user:42", 10*time.Minute,
    func(ctx context.Context) (User, error) { return loadUser(ctx, 42) }, &user)

Index

Constants

This section is empty.

Variables

View Source
var ErrClientRequired = errors.New("cache: redis client is required")

ErrClientRequired 表示未提供 Redis 客户端.

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

ErrNotFound 表示缓存中不存在目标键.

View Source
var ErrWriteFailed = errors.New("cache: write to redis failed")

ErrWriteFailed 表示缓存回写失败(GetOrSet 中视为非致命:结果仍会返回给调用方).

Functions

func GetOrSet

func GetOrSet[T any](c *Cache, ctx context.Context, key string, ttl time.Duration, loader func(context.Context) (T, error), dst *T) error

GetOrSet 缓存未命中时调用 loader 回源,并合并同一 key 的并发加载(singleflight 防击穿)。 同一进程内针对同一 key 的多个并发请求只会触发一次 loader, 其余请求共享同一次结果;loader 的结果回写缓存后返回到 dst.

注意:singleflight 只保护单实例进程,多实例部署时同一 key 可能跨实例回源, 对一致性要求更高的场景请配合分布式锁或短 TTL 使用。

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache 基于 Redis 的类型化缓存.

func New

func New(client redis.UniversalClient) (*Cache, error)

New 创建缓存实例,client 不能为 nil.

func (*Cache) Delete

func (c *Cache) Delete(ctx context.Context, key string) error

Delete 删除缓存键.

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, key string, dst any) error

Get 读取缓存并反序列化到 dst(dst 必须是指针).

func (*Cache) Set

func (c *Cache) Set(ctx context.Context, key string, value any, ttl time.Duration) error

Set 将 value JSON 序列化后写入缓存.

Jump to

Keyboard shortcuts

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