1 Star 0 Fork 0

vgos / plugin

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
redis.go 1.65 KB
一键复制 编辑 原始数据 按行查看 历史
陈仁焕 提交于 2021-11-01 10:27 . fix redis cache plubin
package cache
import (
"encoding/json"
"time"
"gitee.com/vgos/plugin/database"
"github.com/go-redis/redis"
"github.com/pkg/errors"
)
type RedisCache struct {
client *redis.Client
}
func NewRedisCache(conf string) *RedisCache {
instance := &RedisCache{}
instance.client = database.RedisGet(conf)
return instance
}
func (r *RedisCache) Set(key string, value interface{}, ttl time.Duration) error {
return r.client.Set(key, value, ttl).Err()
}
func (r *RedisCache) Get(key string) string {
return r.client.Get(key).String()
}
func (r *RedisCache) GetInt(key string) (int, error) {
return r.client.Get(key).Int()
}
func (r *RedisCache) GetTtl(key string) time.Duration {
return r.client.TTL(key).Val()
}
func (r *RedisCache) SetTtl(key string, ttl time.Duration) bool {
return r.client.Expire(key, ttl).Val()
}
func (r *RedisCache) Remove(key string) int {
i := r.client.Del(key).Val()
return int(i)
}
func (r *RedisCache) Forever(key string, value interface{}) error {
return r.client.Set(key, value, 0).Err()
}
func (r *RedisCache) SetStruct(k string, d interface{}, ttl time.Duration) error {
jsonStr, err := json.Marshal(d)
if err != nil {
return errors.Errorf("save key `%s` json marshal error", k)
}
err = r.Set(k, string(jsonStr), ttl)
if err != nil {
return errors.Errorf("save key `%s` fail:%s", k, err.Error())
}
return nil
}
func (r *RedisCache) GetStruct(k string, data interface{}) error {
valStr, err := r.client.Get(k).Result()
if redis.Nil == err {
return errors.Errorf("key `%s` not found", k)
}
if err != nil {
return errors.Errorf("get key `%s` fail:%s", k, err.Error())
}
return json.Unmarshal([]byte(valStr), &data)
}
1
https://gitee.com/vgos/plugin.git
git@gitee.com:vgos/plugin.git
vgos
plugin
plugin
v0.0.2

搜索帮助

53164aa7 5694891 3bd8fe86 5694891