forked from chenyahui/gin-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
53 lines (43 loc) · 1.2 KB
/
redis.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package persist
import (
"context"
"errors"
"time"
"github.com/go-redis/redis/v8"
)
// RedisStore store http response in redis
type RedisStore struct {
RedisClient *redis.Client
}
// NewRedisStore create a redis memory store with redis client
func NewRedisStore(redisClient *redis.Client) *RedisStore {
return &RedisStore{
RedisClient: redisClient,
}
}
// Set put key value pair to redis, and expire after expireDuration
func (store *RedisStore) Set(key string, value interface{}, expire time.Duration) error {
payload, err := Serialize(value)
if err != nil {
return err
}
ctx := context.TODO()
return store.RedisClient.Set(ctx, key, payload, expire).Err()
}
// Delete remove key in redis, do nothing if key doesn't exist
func (store *RedisStore) Delete(key string) error {
ctx := context.TODO()
return store.RedisClient.Del(ctx, key).Err()
}
// Get retrieves an item from redis, if key doesn't exist, return ErrCacheMiss
func (store *RedisStore) Get(key string, value interface{}) error {
ctx := context.TODO()
payload, err := store.RedisClient.Get(ctx, key).Bytes()
if errors.Is(err, redis.Nil) {
return ErrCacheMiss
}
if err != nil {
return err
}
return Deserialize(payload, value)
}