1 Star 0 Fork 0

小鱼儿小董子/dongli-kit

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
redis_cache.go 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
小鱼儿小董子 提交于 2025-01-14 22:17 +08:00 . 1111
package cache
import (
"context"
"encoding/json"
"time"
"github.com/duke-git/lancet/v2/random"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
"gitee.com/wanjimao/dongli-kit/orm/nosql/key"
)
var (
// ExpireRangeMin is the minimum expire time
ExpireRangeMin = 40 * time.Minute
// ExpireRangeMax is the maximum expire time
ExpireRangeMax = 60 * time.Minute
)
// RedisCache is a redis cache
type RedisCache struct {
logger *zap.Logger
*redis.Client
}
// CreateRedisCache creates a redis cache
func CreateRedisCache(logger *zap.Logger, client *redis.Client) *RedisCache {
return &RedisCache{logger, client}
}
// GetCache gets cache
func (c *RedisCache) GetCache(key key.Key, doc any) bool {
if res := c.Get(context.Background(), key.String()); res.Err() != nil {
return false
} else if data, err := res.Bytes(); err != nil {
return false
} else if err := json.Unmarshal(data, doc); err != nil {
return false
}
return true
}
// SetCache sets cache
func (c *RedisCache) SetCache(key key.Key, doc any) {
expire := random.RandInt(int(ExpireRangeMin), int(ExpireRangeMax))
if data, err := json.Marshal(doc); err != nil {
return
} else if res := c.Set(context.Background(), key.String(), data, time.Duration(expire)); res.Err() != nil {
return
}
}
// DeleteCache deletes cache
func (c *RedisCache) DeleteCache(key key.Key) {
if res := c.Del(context.Background(), key.String()); res.Err() != nil {
return
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wanjimao/dongli-kit.git
git@gitee.com:wanjimao/dongli-kit.git
wanjimao
dongli-kit
dongli-kit
v0.0.37

搜索帮助