83 lines
1.5 KiB
Go
83 lines
1.5 KiB
Go
package redis
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.apinb.com/bsm-sdk/core/errcode"
|
|
)
|
|
|
|
const (
|
|
// 缓存键前缀
|
|
CacheKeyPrefix = "bsm:"
|
|
|
|
// 缓存过期时间
|
|
DefaultTTL = 30 * time.Minute // 30分钟
|
|
)
|
|
|
|
// buildKey 构建缓存键
|
|
func (c *RedisClient) buildKey(prefix string, params ...interface{}) string {
|
|
key := CacheKeyPrefix + prefix
|
|
for _, param := range params {
|
|
key += fmt.Sprintf(":%v", param)
|
|
}
|
|
return key
|
|
}
|
|
|
|
// Get 获取缓存
|
|
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 设置缓存
|
|
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 删除缓存
|
|
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 := 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
|
|
}
|