feat(cache):加入通用的缓存函数。
This commit is contained in:
parent
5ebf6b0431
commit
cf93574294
44
cache/abstract.go
vendored
Normal file
44
cache/abstract.go
vendored
Normal file
|
@ -0,0 +1,44 @@
|
|||
package cache
|
||||
|
||||
import (
|
||||
"electricity_bill_calc/global"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/vmihailenco/msgpack/v5"
|
||||
)
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
Loading…
Reference in New Issue
Block a user