core/cache/redis/cache.go

91 lines
1.9 KiB
Go

// Package redis 提供Redis缓存操作功能
// 包括缓存设置、获取、删除等基本操作
package redis
import (
"encoding/json"
"fmt"
"time"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/vars"
)
// BuildKey 构建缓存键
// prefix: 键前缀
// params: 键参数
// 返回: 完整的缓存键
func (c *RedisClient) BuildKey(prefix string, params ...interface{}) string {
key := vars.CacheKeyPrefix + prefix
for _, param := range params {
key += fmt.Sprintf(":%v", param)
}
return key
}
// Get 获取缓存
// key: 缓存键
// result: 存储结果的指针
// 返回: 错误信息
func (c *RedisClient) Get(key string, result interface{}) error {
if c.Client == nil {
return errcode.ErrRedis
}
data, err := c.Client.Get(c.Ctx, key).Result()
if err != nil {
return errcode.NewError(500, err.Error())
}
return json.Unmarshal([]byte(data), result)
}
// Set 设置缓存
// key: 缓存键
// value: 缓存值
// ttl: 过期时间
// 返回: 错误信息
func (c *RedisClient) Set(key string, value interface{}, ttl time.Duration) error {
if c.Client == nil {
return errcode.ErrRedis
}
data, err := json.Marshal(value)
if err != nil {
return errcode.NewError(500, err.Error())
}
return c.Client.Set(c.Ctx, key, data, ttl).Err()
}
// Delete 删除缓存
// key: 缓存键
// 返回: 错误信息
func (c *RedisClient) Delete(key string) error {
if c.Client == nil {
return errcode.ErrRedis
}
return c.Client.Del(c.Ctx, key).Err()
}
// ClearAllCache 清除所有缓存
// 返回: 错误信息
func (c *RedisClient) ClearAllCache() error {
if c.Client == nil {
return errcode.ErrRedis
}
pattern := vars.CacheKeyPrefix + "*"
keys, err := c.Client.Keys(c.Ctx, pattern).Result()
if err != nil {
return errcode.NewError(500, err.Error())
}
if len(keys) > 0 {
return c.Client.Del(c.Ctx, keys...).Err()
}
return nil
}