forked from sillygod/cdp-cache
/
redis.go
116 lines (96 loc) · 2.31 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
105
106
107
108
109
110
111
112
113
114
115
116
package backends
import (
"bytes"
"context"
"io"
"io/ioutil"
"strconv"
"strings"
"time"
"github.com/go-redis/redis"
)
var (
client *redis.Client
)
// RedisBackend saves the content into redis
type RedisBackend struct {
Ctx context.Context
Key string
content bytes.Buffer
expiration time.Time
}
// ParseRedisConfig parses the connection settings string from the caddyfile
func ParseRedisConfig(connSetting string) (*redis.Options, error) {
var err error
args := strings.Split(connSetting, " ")
addr, password, db := args[0], "", 0
length := len(args)
// the format of args: addr db password
if length > 1 {
db, err = strconv.Atoi(args[1])
if err != nil {
return nil, err
}
}
if length > 2 {
password = args[2]
}
return &redis.Options{
Addr: addr,
DB: db,
Password: password,
}, nil
}
// InitRedisClient inits the client for the redis
func InitRedisClient(addr, password string, db int) error {
l.Lock()
defer l.Unlock()
client = redis.NewClient(&redis.Options{
Addr: addr,
Password: password,
DB: db,
})
if _, err := client.Ping().Result(); err != nil {
return err
}
return nil
}
// NewRedisBackend new a redis backend for cache's storage
func NewRedisBackend(ctx context.Context, key string, expiration time.Time) (Backend, error) {
return &RedisBackend{
Ctx: ctx,
Key: key,
expiration: expiration,
}, nil
}
// Write writes the response content in a temp buffer
func (r *RedisBackend) Write(p []byte) (n int, err error) {
return r.content.Write(p)
}
// Flush do nothing here
func (r *RedisBackend) Flush() error {
return nil
}
// Length return the cache content's length
func (r *RedisBackend) Length() int {
return r.content.Len()
}
// Close write the temp buffer's content to the groupcache
func (r *RedisBackend) Close() error {
_, err := client.Set(r.Key, r.content.Bytes(), r.expiration.Sub(time.Now())).Result()
return err
}
// Clean performs the purge storage
func (r *RedisBackend) Clean() error {
_, err := client.Del(r.Key).Result()
return err
}
// GetReader return a reader for the write public response
func (r *RedisBackend) GetReader() (io.ReadCloser, error) {
content, err := client.Get(r.Key).Result()
if err != nil {
return nil, err
}
rc := ioutil.NopCloser(strings.NewReader(content))
return rc, nil
}