102 lines
2.2 KiB
Go
102 lines
2.2 KiB
Go
package cache
|
|
|
|
import (
|
|
"electricity_bill_calc/global"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-redis/redis/v8"
|
|
"github.com/vmihailenco/msgpack/v5"
|
|
)
|
|
|
|
const (
|
|
TAG_ENTITY = "ENTITY"
|
|
TAG_COUNT = "COUNT"
|
|
TAG_SEARCH = "SEARCH"
|
|
TAG_EXISTS = "CHECK"
|
|
TAG_SESSION = "SESSION"
|
|
TAG_RELATION = "RELATION"
|
|
)
|
|
|
|
// 向Redis缓存中保存一个数据
|
|
// ! 如果需要长期保存一个数据,那么需要向expires传入0。
|
|
func Cache[T interface{}](key string, value *T, expires time.Duration) error {
|
|
serializedValue, err := msgpack.Marshal(value)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cmd := global.RedisConn.Set(global.Ctx, key, serializedValue, expires)
|
|
return cmd.Err()
|
|
}
|
|
|
|
// 从Redis缓存中获取一个数据
|
|
func Retreive[T interface{}](key string) (*T, error) {
|
|
result, err := global.RedisConn.Get(global.Ctx, key).Result()
|
|
if err != nil {
|
|
if err == redis.Nil {
|
|
return nil, nil
|
|
} else {
|
|
return nil, err
|
|
}
|
|
}
|
|
value := new(T)
|
|
err = msgpack.Unmarshal([]byte(result), value)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
// 检查Redis缓存中是否存在指定键的记录
|
|
func Exists(key string) (bool, error) {
|
|
result, err := global.RedisConn.Exists(global.Ctx, key).Result()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return result > 0, nil
|
|
}
|
|
|
|
// 从Redis缓存中删除指定键
|
|
// ! 如果指定键已不存在,那么本函数一样会返回false
|
|
func Delete(key string) (bool, error) {
|
|
result, err := global.RedisConn.Del(global.Ctx, key).Result()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return result > 0, nil
|
|
}
|
|
|
|
// 从Redis缓存中批量删除符合pattern的键,这里的pattern直接使用Redis的pattern规则
|
|
func DeleteAll(pattern string) error {
|
|
var (
|
|
cursor uint64
|
|
keys = make([]string, 0)
|
|
)
|
|
for {
|
|
k, cursor, err := global.RedisConn.Scan(global.Ctx, cursor, pattern, 20).Result()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
keys = append(keys, k...)
|
|
if cursor == 0 {
|
|
break
|
|
}
|
|
}
|
|
pipeline := global.RedisConn.Pipeline()
|
|
pipeline.Del(global.Ctx, keys...)
|
|
_, err := pipeline.Exec(global.Ctx)
|
|
return err
|
|
}
|
|
|
|
// 生成用于Redis存储的键
|
|
func CacheKey(category string, ids ...string) string {
|
|
var b strings.Builder
|
|
b.WriteString(category)
|
|
for _, s := range ids {
|
|
fmt.Fprintf(&b, ":%s", s)
|
|
}
|
|
return b.String()
|
|
}
|