package cache import ( "context" "encoding/json" "os" "time" ) var ( std Cache ) func init() { std = NewMemCache() } func SetCache(l Cache) { std = l } func GetCache() Cache { return std } // Set 设置缓存数据 func Set(ctx context.Context, key string, buf []byte) { std.Set(ctx, key, buf) } // SetEx 设置一个有效时间的缓存数据 func SetEx(ctx context.Context, key string, buf []byte, expire time.Duration) { std.SetEx(ctx, key, buf, expire) } // Try 尝试获取缓存数据,获取不到就设置 func Try(ctx context.Context, key string, cb LoadFunc) (buf []byte, err error) { return std.Try(ctx, key, cb) } // Get 获取缓存数据 func Get(ctx context.Context, key string) (buf []byte, ok bool) { return std.Get(ctx, key) } // Del 删除缓存数据 func Del(ctx context.Context, key string) { std.Del(ctx, key) } // Store 存储缓存数据 func Store(ctx context.Context, key string, val any) (err error) { return StoreEx(ctx, key, val, 0) } // StoreEx 存储缓存数据 func StoreEx(ctx context.Context, key string, val any, expire time.Duration) (err error) { var ( buf []byte ) if buf, err = json.Marshal(val); err != nil { return } SetEx(ctx, key, buf, expire) return } // Load 加载指定的缓存数据 func Load(ctx context.Context, key string, val any) (err error) { var ( ok bool buf []byte ) if buf, ok = Get(ctx, key); !ok { return os.ErrNotExist } err = json.Unmarshal(buf, val) return }