Documentation
¶
Overview ¶
Package cache 统一的缓存系统接口
Index ¶
Constants ¶
View Source
const Forever = 0
Forever 永不过时
Variables ¶
This section is empty.
Functions ¶
func GetOrInit ¶ added in v0.11.0
func GetOrInit[T any](cache Cache, key string, v *T, ttl time.Duration, init func() (T, error)) error
GetOrInit 获取缓存项
在缓存不存在时,会尝试调用 init 初始化,并调用 [Cache.Set] 存入缓存。
key 和 v 相当于调用 [Cache.Get] 的参数; 如果 [Cache.Get] 返回 ErrCacheMiss,那么将调用 init 方法初始化值并写入缓存, 最后再调用 [Cache.Get] 返回值。
Types ¶
type Cache ¶
type Cache interface {
// Get 获取缓存项
//
// 当前不存在时,返回 [ErrCacheMiss] 错误。
// key 为缓存项的唯一 ID;
// v 为缓存写入的地址,应该始终为指针类型;
Get(key string, v any) error
// Set 设置或是添加缓存项
//
// key 表示保存该数据的唯一 ID;
// val 表示保存的数据对象,如果是结构体,则会调用 gob 包进行序列化。
// ttl 表示过了该时间,缓存项将被回收。如果该值为 [Forever],该值永远不会回收。
Set(key string, val any, ttl time.Duration) error
// Delete 删除一个缓存项
//
// 如果该项目不存在,则返回 nil。
Delete(string) error
// Exists 判断一个缓存项是否存在
Exists(string) bool
// Counter 返回计数器操作接口
//
// key 表示计数器的名称,如果已经存在同名值,那么将被覆盖。
// val 和 ttl 表示在该计数器不存在时,初始化的值以及回收时间。
Counter(key string, val uint64, ttl time.Duration) (Counter, error)
}
Cache 缓存内容的访问接口
Click to show internal directories.
Click to hide internal directories.