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.
dorm/redis_cache.go

97 lines
2.4 KiB

package dorm
import (
"context"
4 months ago
"go.dtapp.net/gojson"
"time"
)
2 years ago
// GttStringFunc String缓存结构
type GttStringFunc func() string
// GttInterfaceFunc Interface缓存结构
type GttInterfaceFunc func() interface{}
// RedisCacheConfig 配置
type RedisCacheConfig struct {
2 years ago
Expiration time.Duration // 过期时间
}
// RedisClientCache https://github.com/go-redis/redis
type RedisClientCache struct {
2 years ago
defaultExpiration time.Duration // 过期时间
operation *RedisClient // 操作
GetterString GttStringFunc // 不存在的操作
GetterInterface GttInterfaceFunc // 不存在的操作
}
// NewCache 实例化
2 years ago
func (r *RedisClient) NewCache(config *RedisCacheConfig) *RedisClientCache {
return &RedisClientCache{
defaultExpiration: config.Expiration,
operation: r,
}
}
// NewCacheDefaultExpiration 实例化
2 years ago
func (r *RedisClient) NewCacheDefaultExpiration() *RedisClientCache {
return &RedisClientCache{
defaultExpiration: time.Minute * 30,
operation: r,
}
}
// GetString 缓存操作
func (rc *RedisClientCache) GetString(ctx context.Context, key string) (ret string) {
f := func() string {
return rc.GetterString()
}
// 如果不存在则调用GetterString
ret, err := rc.operation.Get(ctx, key).Result()
if err != nil {
2 years ago
rc.operation.Set(ctx, key, f(), rc.defaultExpiration)
ret, _ = rc.operation.Get(ctx, key).Result()
}
return
}
// GetInterface 缓存操作
func (rc *RedisClientCache) GetInterface(ctx context.Context, key string, result interface{}) {
f := func() string {
4 months ago
marshal, _ := gojson.Marshal(rc.GetterInterface())
return string(marshal)
}
// 如果不存在则调用GetterInterface
ret, err := rc.operation.Get(ctx, key).Result()
if err != nil {
2 years ago
rc.operation.Set(ctx, key, f(), rc.defaultExpiration)
ret, _ = rc.operation.Get(ctx, key).Result()
}
4 months ago
err = gojson.Unmarshal([]byte(ret), result)
return
}
// GetInterfaceKey 获取key值
func (rc *RedisClientCache) GetInterfaceKey(ctx context.Context, key string, result interface{}) error {
ret, err := rc.operation.Get(ctx, key).Result()
if err != nil {
return err
}
4 months ago
err = gojson.Unmarshal([]byte(ret), result)
return nil
}
// SetInterfaceKey 设置key值
func (rc *RedisClientCache) SetInterfaceKey(ctx context.Context, key string, value interface{}) (string, error) {
4 months ago
marshal, _ := gojson.Marshal(value)
2 years ago
return rc.operation.Set(ctx, key, marshal, rc.defaultExpiration).Result()
}