Ai
1 Star 0 Fork 0

masaichi/工具包

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
SimpleCache.go 1.34 KB
一键复制 编辑 原始数据 按行查看 历史
邓正锋 提交于 2024-05-17 16:02 +08:00 . 添加redis操作方法
package goredis
import (
"encoding/json"
"time"
)
const (
Serilizer_JSON = "json"
)
type DBGettFunc func() interface{}
type SimpleCache struct {
Operation *StringOperation
Expire time.Duration
DBGeter DBGettFunc
Serilizer string
}
func NewSimpleCache(operation *StringOperation, expire time.Duration, serilizer string) *SimpleCache {
return &SimpleCache{Operation: operation, Expire: expire, Serilizer: serilizer}
}
// 设置缓存
func (this *SimpleCache) SetCache(key string, value interface{}, expire time.Duration) {
this.Operation.Set(key, value, WithExpire(expire)).UnWrap()
}
// 获取缓存
func (this *SimpleCache) GetCache(key string) (ret interface{}) {
if this.Serilizer == Serilizer_JSON {
//转成字符串
f := func() string {
if this.DBGeter == nil {
return ""
} else {
obj := this.DBGeter()
b, err := json.Marshal(obj)
if err != nil {
return ""
}
return string(b)
}
}
ret = this.Operation.Get(key).UnwrapElse(f)
this.SetCache(key, ret, this.Expire)
}
return
}
// /锁
func (this *SimpleCache) Lock(key string, exp time.Duration) bool {
return this.Operation.SetNx(key, 1, WithExpire(exp)).UnWrap().(bool)
}
// 解锁
func (this *SimpleCache) Unlock(key string) {
this.Operation.Del(key)
}
// 删除缓存
func (this *SimpleCache) Del(key string) {
this.Operation.Del(key)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/masaichi/mastool.git
git@gitee.com:masaichi/mastool.git
masaichi
mastool
工具包
v0.0.4

搜索帮助