/
redis.go
104 lines (85 loc) · 2.28 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
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
99
100
101
102
103
104
package lib
import (
"context"
"fmt"
"time"
"github.com/RealLiuSha/echo-admin/constants"
"github.com/RealLiuSha/echo-admin/errors"
"github.com/go-redis/cache/v8"
"github.com/go-redis/redis/v8"
)
type Redis struct {
cache *cache.Cache
client *redis.Client
prefix string
}
// NewRedis creates a new redis client instance
func NewRedis(config Config, logger Logger) Redis {
addr := config.Redis.Addr()
client := redis.NewClient(&redis.Options{
Addr: addr,
DB: constants.RedisMainDB,
Password: config.Redis.Password,
})
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if _, err := client.Ping(ctx).Result(); err != nil {
logger.Zap.Fatalf("Error to open redis[%s] connection: %v", addr, err)
}
logger.Zap.Info("Redis connection established")
return Redis{
client: client,
prefix: config.Redis.KeyPrefix,
cache: cache.New(&cache.Options{
Redis: client,
LocalCache: cache.NewTinyLFU(1000, time.Minute),
}),
}
}
func (a Redis) wrapperKey(key string) string {
return fmt.Sprintf("%s:%s", a.prefix, key)
}
func (a Redis) Set(key string, value interface{}, expiration time.Duration) error {
return a.cache.Set(&cache.Item{
Ctx: context.TODO(),
Key: a.wrapperKey(key),
Value: value,
TTL: expiration,
SkipLocalCache: true,
})
}
func (a Redis) Get(key string, value interface{}) error {
err := a.cache.Get(context.TODO(), a.wrapperKey(key), value)
if err == cache.ErrCacheMiss {
err = errors.RedisKeyNoExist
}
return err
}
func (a Redis) Delete(keys ...string) (bool, error) {
wrapperKeys := make([]string, len(keys))
for index, key := range keys {
wrapperKeys[index] = a.wrapperKey(key)
}
cmd := a.client.Del(context.TODO(), wrapperKeys...)
if err := cmd.Err(); err != nil {
return false, err
}
return cmd.Val() > 0, nil
}
func (a Redis) Check(keys ...string) (bool, error) {
wrapperKeys := make([]string, len(keys))
for index, key := range keys {
wrapperKeys[index] = a.wrapperKey(key)
}
cmd := a.client.Exists(context.TODO(), wrapperKeys...)
if err := cmd.Err(); err != nil {
return false, err
}
return cmd.Val() > 0, nil
}
func (a Redis) Close() error {
return a.client.Close()
}
func (a Redis) GetClient() *redis.Client {
return a.client
}