-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcache_redis.go
278 lines (245 loc) · 6.23 KB
/
cache_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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package kuu
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/go-redis/redis/v8"
"os"
"strconv"
"strings"
"time"
)
// CacheRedis
type CacheRedis struct {
client redis.UniversalClient
}
// GetRedisClient
func GetRedisClient() redis.UniversalClient {
return DefaultCache.(*CacheRedis).client
}
// BuildKey
func BuildKey(keys ...string) string {
var (
rawKey = strings.Join(keys, "_")
appPrefix = GetAppName()
)
if strings.HasPrefix(rawKey, appPrefix) {
return rawKey
}
return fmt.Sprintf("%s_%s", appPrefix, rawKey)
}
func (c *CacheRedis) buildKeyAndExp(key string, expiration []time.Duration) (string, time.Duration) {
key = BuildKey(key)
var exp time.Duration
if len(expiration) > 0 {
exp = expiration[0]
}
return key, exp
}
// NewCacheRedis
func NewCacheRedis() *CacheRedis {
GetAppName()
var (
c = &CacheRedis{}
)
// 解析配置
var opts redis.UniversalOptions
C().GetInterface("redis", &opts)
redisTls := C().GetString("redis.caPath")
if len(redisTls) > 0 {
caCert, err := os.ReadFile(redisTls)
if err != nil {
fmt.Println("Error loading CA certificate:", err)
PANIC(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
RootCAs: caCertPool,
InsecureSkipVerify: true, // Not actually skipping, we check the cert in VerifyPeerCertificate
VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
certs := make([]*x509.Certificate, len(rawCerts))
for i, asn1Data := range rawCerts {
cert, err := x509.ParseCertificate(asn1Data)
if err != nil {
panic(err)
}
certs[i] = cert
}
opts := x509.VerifyOptions{
Roots: caCertPool,
DNSName: "", // <- skip hostname verification
Intermediates: x509.NewCertPool(),
}
for i, cert := range certs {
if i == 0 {
continue
}
opts.Intermediates.AddCert(cert)
}
_, err := certs[0].Verify(opts)
return err
},
}
opts.TLSConfig = tlsConfig
}
// 初始化客户端
cmd := redis.NewUniversalClient(&opts)
if _, err := cmd.Ping(context.Background()).Result(); err != nil {
PANIC(err)
}
c.client = cmd
connectedPrint(strings.Title("redis"), strings.Join(opts.Addrs, ","))
return c
}
// SetString
func (c *CacheRedis) SetString(rawKey, val string, expiration ...time.Duration) {
var (
key, exp = c.buildKeyAndExp(rawKey, expiration)
status = c.client.Set(context.Background(), key, val, exp)
)
if err := status.Err(); err != nil {
ERROR(err)
}
}
// GetString
func (c *CacheRedis) GetString(rawKey string) (val string) {
var (
key = BuildKey(rawKey)
cmd = c.client.Get(context.Background(), key)
)
return cmd.Val()
}
func (c *CacheRedis) scan(cursor uint64, pattern string, limit int64) (values map[string]string) {
values = make(map[string]string)
for len(values) < int(limit) {
cmd := c.client.Scan(context.Background(), cursor, pattern, limit)
if err := cmd.Err(); err != nil {
ERROR(err)
return
}
if keys, nextCur := cmd.Val(); len(keys) > 0 {
for _, key := range keys {
values[key] = c.client.Get(context.Background(), key).Val()
}
if (limit != 0 && len(values) >= int(limit)) || nextCur == 0 {
break
} else {
cursor = nextCur
}
} else {
break
}
}
return
}
// HasPrefix
func (c *CacheRedis) HasPrefix(rawKey string, limit int) map[string]string {
pattern := BuildKey(rawKey)
if !strings.HasSuffix(pattern, "*") {
pattern = fmt.Sprintf("%s*", pattern)
}
return c.scan(0, pattern, int64(limit))
}
// HasSuffix
func (c *CacheRedis) HasSuffix(rawKey string, limit int) map[string]string {
pattern := BuildKey(rawKey)
if !strings.HasPrefix(pattern, "*") {
pattern = fmt.Sprintf("*%s", pattern)
}
return c.scan(0, pattern, int64(limit))
}
// Contains
func (c *CacheRedis) Contains(rawKey string, limit int) map[string]string {
pattern := BuildKey(rawKey)
if !strings.HasPrefix(pattern, "*") {
pattern = fmt.Sprintf("*%s", pattern)
}
if !strings.HasSuffix(pattern, "*") {
pattern = fmt.Sprintf("%s*", pattern)
}
return c.scan(0, pattern, int64(limit))
}
// SetInt
func (c *CacheRedis) SetInt(rawKey string, val int, expiration ...time.Duration) {
c.SetString(rawKey, strconv.Itoa(val), expiration...)
}
// GetInt
func (c *CacheRedis) GetInt(key string) (val int) {
if v, err := strconv.Atoi(c.GetString(key)); err == nil {
val = v
}
return
}
// Incr
func (c *CacheRedis) Incr(rawKey string) (val int) {
var (
key = BuildKey(rawKey)
cmd = c.client.Incr(context.Background(), key)
)
if err := cmd.Err(); err != nil {
ERROR(err)
} else {
val = int(cmd.Val())
}
return
}
// Del
func (c *CacheRedis) Del(keys ...string) {
for index, key := range keys {
keys[index] = BuildKey(key)
}
cmd := c.client.Del(context.Background(), keys...)
if err := cmd.Err(); err != nil {
ERROR(err)
}
}
// Close
func (c *CacheRedis) Close() {
if c.client != nil {
ERROR(c.client.Close())
}
}
func (c *CacheRedis) Publish(channel string, message interface{}) error {
return c.client.Publish(context.Background(), channel, message).Err()
}
func (c *CacheRedis) Subscribe(channels []string, handler func(string, string)) error {
ps := c.client.Subscribe(context.Background(), channels...)
if _, err := ps.Receive(context.Background()); err != nil {
return err
}
ch := ps.Channel()
go func(ch <-chan *redis.Message) {
for msg := range ch {
handler(msg.Channel, msg.Payload)
}
}(ch)
return nil
}
func (c *CacheRedis) PSubscribe(patterns []string, handler func(string, string)) error {
pubsub := c.client.PSubscribe(context.Background(), patterns...)
if _, err := pubsub.Receive(context.Background()); err != nil {
return err
}
ch := pubsub.Channel()
go func(ch <-chan *redis.Message) {
for msg := range ch {
handler(msg.Channel, msg.Payload)
}
}(ch)
return nil
}
func (c *CacheRedis) HGetAll(key string) map[string]string {
return c.client.HGetAll(context.Background(), key).Val()
}
func (c *CacheRedis) HGet(key, field string) string {
return c.client.HGet(context.Background(), key, field).Val()
}
func (c *CacheRedis) HSet(key string, values ...string) {
var vs []interface{}
for _, value := range values {
vs = append(vs, value)
}
c.client.HSet(context.Background(), key, vs...)
}