From db03af4a08004651eeef51b5d2be7e026f7228b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=85=89=E6=98=A5?= Date: Sat, 7 May 2022 09:31:35 +0800 Subject: [PATCH] update redis --- connom.go | 2 +- redis.go | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/connom.go b/connom.go index 8009ed1..d566bb4 100644 --- a/connom.go +++ b/connom.go @@ -2,7 +2,7 @@ package gocache import "time" -const Version = "1.0.1" +const Version = "1.0.2" var ( DefaultExpiration = time.Minute * 30 // 默认过期时间 diff --git a/redis.go b/redis.go index 1f58426..8208340 100644 --- a/redis.go +++ b/redis.go @@ -2,6 +2,7 @@ package gocache import ( "context" + "encoding/json" "errors" "fmt" "github.com/go-redis/redis/v8" @@ -45,16 +46,38 @@ func (r *Redis) Set(key string, value interface{}, expiration time.Duration) (st return r.db.Set(r.ctx, key, value, expiration).Result() } +// SetInterface 设置一个key的值 +func (r *Redis) SetInterface(key string, value interface{}, expiration time.Duration) (string, error) { + marshal, _ := json.Marshal(value) + return r.db.Set(r.ctx, key, marshal, expiration).Result() +} + // SetDefaultExpiration 设置一个key的值,使用全局默认过期时间 func (r *Redis) SetDefaultExpiration(key string, value interface{}) (string, error) { return r.db.Set(r.ctx, key, value, r.expiration).Result() } +// SetInterfaceDefaultExpiration 设置一个key的值,使用全局默认过期时间 +func (r *Redis) SetInterfaceDefaultExpiration(key string, value interface{}) (string, error) { + marshal, _ := json.Marshal(value) + return r.db.Set(r.ctx, key, marshal, r.expiration).Result() +} + // Get 查询key的值 func (r *Redis) Get(key string) (string, error) { return r.db.Get(r.ctx, key).Result() } +// GetInterface 查询key的值 +func (r *Redis) GetInterface(key string, result interface{}) error { + ret, err := r.db.Get(r.ctx, key).Result() + if err != nil { + return err + } + err = json.Unmarshal([]byte(ret), result) + return nil +} + // GetSet 设置一个key的值,并返回这个key的旧值 func (r *Redis) GetSet(key string, value interface{}) (string, error) { return r.db.GetSet(r.ctx, key, value).Result()