You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gocache/redis_cache.go

58 lines
1.2 KiB

2 years ago
package gocache
import (
2 years ago
"encoding/json"
2 years ago
"time"
)
// RedisCache https://github.com/go-redis/redis
type RedisCache struct {
db *Redis // 驱动
expiration time.Duration // 默认过期时间
GetterString GttStringFunc // 不存在的操作
GetterInterface GttInterfaceFunc // 不存在的操作
}
// NewCache 返回Redis缓存实例
func (r *Redis) NewCache(expiration time.Duration) *RedisCache {
2 years ago
return &RedisCache{db: r, expiration: expiration}
2 years ago
}
2 years ago
// GetString 缓存操作
func (rc *RedisCache) GetString(key string) (ret string) {
2 years ago
2 years ago
f := func() string {
return rc.GetterString()
2 years ago
}
2 years ago
// 如果不存在则调用GetterString
2 years ago
ret, err := rc.db.Get(key)
if err != nil {
2 years ago
rc.db.Set(key, f(), rc.expiration)
2 years ago
ret, _ = rc.db.Get(key)
}
return
}
2 years ago
// GetInterface 缓存操作
func (rc *RedisCache) GetInterface(key string, result interface{}) {
2 years ago
f := func() string {
2 years ago
marshal, _ := json.Marshal(rc.GetterInterface())
return string(marshal)
2 years ago
}
2 years ago
// 如果不存在则调用GetterInterface
2 years ago
ret, err := rc.db.Get(key)
2 years ago
2 years ago
if err != nil {
2 years ago
rc.db.Set(key, f(), rc.expiration)
ret, _ = rc.db.Get(key)
2 years ago
}
2 years ago
err = json.Unmarshal([]byte(ret), result)
2 years ago
return
}