This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
redis.go
71 lines (58 loc) · 1.64 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package cache
import (
"context"
"time"
"github.com/Shopify/go-encoding"
"github.com/go-redis/redis/v8"
)
func NewRedisClient(c *redis.Client, enc encoding.ValueEncoding) Client {
return &redisClient{client: c, encoding: enc}
}
type redisClient struct {
client *redis.Client
encoding encoding.ValueEncoding
}
func (c *redisClient) Get(ctx context.Context, key string, data interface{}) error {
cmd := c.client.Get(ctx, key)
b, err := cmd.Bytes()
if err != nil {
if err == redis.Nil {
return ErrCacheMiss
}
return err
}
return c.encoding.Decode(b, data)
}
func (c *redisClient) Set(ctx context.Context, key string, data interface{}, expiration time.Time) error {
data, err := c.encoding.Encode(data)
if err != nil {
return err
}
cmd := c.client.Set(ctx, key, data, ttlForExpiration(expiration))
return cmd.Err()
}
func (c *redisClient) Add(ctx context.Context, key string, data interface{}, expiration time.Time) error {
b, err := c.encoding.Encode(data)
if err != nil {
return err
}
cmd := c.client.SetNX(ctx, key, b, ttlForExpiration(expiration))
if !cmd.Val() {
return ErrNotStored
}
return cmd.Err()
}
func (c *redisClient) Delete(ctx context.Context, key string) error {
err := c.client.Del(ctx, key)
return err.Err()
}
func (c *redisClient) Increment(ctx context.Context, key string, delta uint64) (uint64, error) {
cmd := c.client.IncrBy(ctx, key, int64(delta))
val, err := cmd.Result()
return uint64(val), err
}
func (c *redisClient) Decrement(ctx context.Context, key string, delta uint64) (uint64, error) {
cmd := c.client.DecrBy(ctx, key, int64(delta))
val, err := cmd.Result()
return uint64(val), err
}