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

73 lines
1.5 KiB

2 years ago
package gocache
import (
5 months ago
"go.dtapp.net/gojson"
2 years ago
"time"
)
2 years ago
// RedisCacheConfig 配置
type RedisCacheConfig struct {
expiration time.Duration // 过期时间
}
2 years ago
// RedisCache https://github.com/go-redis/redis
type RedisCache struct {
2 years ago
config *RedisCacheConfig
operation *Redis // 操作
2 years ago
GetterString GttStringFunc // 不存在的操作
GetterInterface GttInterfaceFunc // 不存在的操作
}
// NewCache 实例化
2 years ago
func (r *Redis) NewCache(config *RedisCacheConfig) *RedisCache {
2 years ago
c := &RedisCache{config: config}
c.operation = r
return c
2 years ago
}
// NewCacheDefaultExpiration 实例化
func (r *Redis) NewCacheDefaultExpiration() *RedisCache {
2 years ago
c := &RedisCache{}
c.config.expiration = r.config.DefaultExpiration
c.operation = r
return c
}
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.operation.Get(key)
2 years ago
if err != nil {
2 years ago
rc.operation.Set(key, f(), rc.config.expiration)
ret, _ = rc.operation.Get(key)
2 years ago
}
return
}
2 years ago
// GetInterface 缓存操作
func (rc *RedisCache) GetInterface(key string, result interface{}) {
2 years ago
f := func() string {
5 months ago
marshal, _ := gojson.Marshal(rc.GetterInterface())
2 years ago
return string(marshal)
2 years ago
}
2 years ago
// 如果不存在则调用GetterInterface
2 years ago
ret, err := rc.operation.Get(key)
2 years ago
2 years ago
if err != nil {
2 years ago
rc.operation.Set(key, f(), rc.config.expiration)
ret, _ = rc.operation.Get(key)
2 years ago
}
5 months ago
err = gojson.Unmarshal([]byte(ret), result)
2 years ago
2 years ago
return
}