-
Notifications
You must be signed in to change notification settings - Fork 0
/
rediscache.go
98 lines (87 loc) · 2.48 KB
/
rediscache.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package rediscache
import (
"context"
"encoding/json"
"github.com/go-redis/redis/v8"
"github.com/mitchellh/mapstructure"
"time"
)
type Options redis.Options
type cache struct {
expire time.Duration
client *redis.Client
}
type Cache interface {
Get(ctx context.Context, key string, expectedValue interface{}) (interface{}, error)
Set(ctx context.Context, key string, value interface{}) error
}
func NewRedisCache(
expire time.Duration,
redisOptions Options) Cache {
options := func(redisOptions Options) *redis.Options {
return &redis.Options{
Network: redisOptions.Network,
Addr: redisOptions.Addr,
Dialer: redisOptions.Dialer,
OnConnect: redisOptions.OnConnect,
Username: redisOptions.Username,
Password: redisOptions.Password,
DB: redisOptions.DB,
MaxRetries: redisOptions.MaxRetries,
MinRetryBackoff: redisOptions.MinRetryBackoff,
MaxRetryBackoff: redisOptions.MaxRetryBackoff,
DialTimeout: redisOptions.DialTimeout,
ReadTimeout: redisOptions.ReadTimeout,
WriteTimeout: redisOptions.WriteTimeout,
PoolFIFO: redisOptions.PoolFIFO,
PoolSize: redisOptions.PoolSize,
MinIdleConns: redisOptions.MinIdleConns,
MaxConnAge: redisOptions.MaxConnAge,
PoolTimeout: redisOptions.PoolTimeout,
IdleTimeout: redisOptions.IdleTimeout,
IdleCheckFrequency: redisOptions.IdleCheckFrequency,
TLSConfig: redisOptions.TLSConfig,
Limiter: redisOptions.Limiter,
}
}(redisOptions)
redisClient := redis.NewClient(options)
return &cache{
expire: expire,
client: redisClient,
}
}
func (c *cache) Get(ctx context.Context, key string, expectedValue interface{}) (
interface{},
error,
) {
var err error
result, err := c.client.Get(ctx, key).Result()
if err != nil {
return expectedValue, err
}
var resultMap map[string]interface{}
err = json.Unmarshal([]byte(result), &resultMap)
if err != nil {
return expectedValue, err
}
cfg := &mapstructure.DecoderConfig{
Metadata: nil,
Result: &expectedValue,
TagName: "json",
}
decoder, _ := mapstructure.NewDecoder(cfg)
decoder.Decode(resultMap)
return expectedValue, err
}
func (c *cache) Set(
ctx context.Context,
key string,
value interface{},
) (err error) {
valueByte, err := json.Marshal(value)
if err != nil {
return err
}
c.client.Set(ctx, key, valueByte, c.expire*time.Minute)
return err
}