github.com/aaabigfish/gopkg@v1.1.0/cache/redis/redis.go (about) 1 package redis 2 3 import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "time" 8 9 gredis "github.com/redis/go-redis/v9" 10 ) 11 12 // Client redis 客户端 13 type Client struct { 14 gredis.UniversalClient 15 } 16 17 // Get 获取缓存实例 18 func NewClient(dsn string) *Client { 19 opts := &gredis.UniversalOptions{} 20 21 setOptions(opts, dsn) 22 23 rdb := gredis.NewUniversalClient(opts) 24 25 db := &Client{rdb} 26 27 return db 28 29 } 30 31 func (c *Client) SaveStruct(ctx context.Context, key string, data interface{}, second int) error { 32 bData, err := json.Marshal(data) 33 if err != nil { 34 return fmt.Errorf("save key(%s) json.Marshal(%v) err(%v)", key, data, err) 35 } 36 err = c.Set(ctx, key, string(bData), time.Duration(second)*time.Second).Err() 37 if err != nil { 38 return fmt.Errorf("save key(%s) fail:%s", key, err.Error()) 39 } 40 return nil 41 } 42 43 func (c *Client) GetStruct(ctx context.Context, key string, data interface{}) error { 44 valStr, err := c.Get(ctx, key).Result() 45 if gredis.Nil == err { 46 return fmt.Errorf("key(%s) not found", key) 47 } 48 if err != nil { 49 return fmt.Errorf("get key(%s) fail:%s", key, err.Error()) 50 } 51 return json.Unmarshal([]byte(valStr), &data) 52 }