59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
package cache
|
||
|
||
import (
|
||
"electricity_bill_calc/global"
|
||
"time"
|
||
|
||
"github.com/go-redis/redis/v8"
|
||
"github.com/vmihailenco/msgpack/v5"
|
||
)
|
||
|
||
// 向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.SetEX(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
|
||
}
|