|
@@ -2,6 +2,8 @@ package cache
|
|
|
|
|
|
import (
|
|
|
"context"
|
|
|
+ "encoding/json"
|
|
|
+ "os"
|
|
|
"time"
|
|
|
)
|
|
|
|
|
@@ -21,22 +23,57 @@ func GetCache() Cache {
|
|
|
return std
|
|
|
}
|
|
|
|
|
|
-func Set(ctx context.Context, key string, value any) {
|
|
|
- std.Set(ctx, key, value)
|
|
|
+// Set 设置缓存数据
|
|
|
+func Set(ctx context.Context, key string, buf []byte) {
|
|
|
+ std.Set(ctx, key, buf)
|
|
|
}
|
|
|
|
|
|
-func SetEx(ctx context.Context, key string, value any, expire time.Duration) {
|
|
|
- std.SetEx(ctx, key, value, expire)
|
|
|
+// SetEx 设置一个有效时间的缓存数据
|
|
|
+func SetEx(ctx context.Context, key string, buf []byte, expire time.Duration) {
|
|
|
+ std.SetEx(ctx, key, buf, expire)
|
|
|
}
|
|
|
|
|
|
-func Try(ctx context.Context, key string, cb LoadFunc) (value any, err error) {
|
|
|
+// Try 尝试获取缓存数据,获取不到就设置
|
|
|
+func Try(ctx context.Context, key string, cb LoadFunc) (buf []byte, err error) {
|
|
|
return std.Try(ctx, key, cb)
|
|
|
}
|
|
|
|
|
|
-func Get(ctx context.Context, key string) (value any, ok bool) {
|
|
|
+// 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
|
|
|
+}
|