kos/pkg/cache/instance.go

80 lines
1.4 KiB
Go
Raw Normal View History

2023-04-23 17:57:36 +08:00
package cache
import (
"context"
2023-09-20 11:05:08 +08:00
"encoding/json"
"os"
2023-04-23 17:57:36 +08:00
"time"
)
var (
std Cache
)
func init() {
std = NewMemCache()
}
func SetCache(l Cache) {
std = l
}
func GetCache() Cache {
return std
}
2023-09-20 11:05:08 +08:00
// Set 设置缓存数据
func Set(ctx context.Context, key string, buf []byte) {
std.Set(ctx, key, buf)
2023-04-23 17:57:36 +08:00
}
2023-09-20 11:05:08 +08:00
// SetEx 设置一个有效时间的缓存数据
func SetEx(ctx context.Context, key string, buf []byte, expire time.Duration) {
std.SetEx(ctx, key, buf, expire)
2023-04-23 17:57:36 +08:00
}
2023-09-20 11:05:08 +08:00
// Try 尝试获取缓存数据,获取不到就设置
func Try(ctx context.Context, key string, cb LoadFunc) (buf []byte, err error) {
2023-06-30 14:16:16 +08:00
return std.Try(ctx, key, cb)
}
2023-09-20 11:05:08 +08:00
// Get 获取缓存数据
func Get(ctx context.Context, key string) (buf []byte, ok bool) {
2023-04-23 17:57:36 +08:00
return std.Get(ctx, key)
}
2023-09-20 11:05:08 +08:00
// Del 删除缓存数据
2023-04-23 17:57:36 +08:00
func Del(ctx context.Context, key string) {
std.Del(ctx, key)
}
2023-09-20 11:05:08 +08:00
// 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
}