-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
66 lines (56 loc) · 1.38 KB
/
cache.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
package dataful
import (
"context"
"encoding/json"
"time"
"github.com/go-redis/redis/v8"
)
//Cache interface.
type Cache interface {
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
Get(ctx context.Context, key string, document interface{}) error
}
//Redis implements cache interface.
type Redis struct {
c *redis.Client
}
//NewRedis initializes and returns a new redis client.
func NewRedis(ctx context.Context, redisURI string, redisPassword string) (*Redis, error) {
redis := redis.NewClient(&redis.Options{
Addr: redisURI,
Password: redisPassword,
DB: 0,
})
rx := redis.Ping(ctx)
if rx.Err() != nil {
return nil, rx.Err()
}
return &Redis{
c: redis,
}, nil
}
//Get gets data from cache and unmarshals the data to provided document.
func (r *Redis) Get(ctx context.Context, key string, document interface{}) error {
result := r.c.Get(ctx, key)
if result.Err() != nil {
return result.Err()
}
b, err := result.Bytes()
if err != nil {
return err
}
err = json.Unmarshal(b, document)
if err != nil {
return err
}
return nil
}
//Set marshals the given value and adds it to cache.
func (r *Redis) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
status := r.c.Set(ctx, key, data, expiration)
return status.Err()
}