-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis-cache.go
253 lines (198 loc) · 5.56 KB
/
redis-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
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
package main
import (
"fmt"
"log"
"net"
"net/http"
"regexp"
"sync"
"time"
"github.com/gorilla/mux"
lru "github.com/hashicorp/golang-lru"
"github.com/mediocregopher/radix.v2/redis"
)
var redisClient *redis.Client
type lockableCache struct {
// lru.Cache is threadsafe but it is exported
// without a mutex.
// Sometimes (as in expireRedisCache() method)
// need to lock the cache as a whole.
lru *lru.Cache
lock *sync.RWMutex
}
var redisCache lockableCache
var expiryStop chan bool
var cacheHit int // not threadsafe, purely for testing
var cacheMiss int // not threadsafe, purely for testing
func clearCacheStats() {
cacheHit = 0
cacheMiss = 0
}
type valueStruct struct {
value string
expiryTime int64
}
func healthCheck(w http.ResponseWriter, req *http.Request) {
res, err := redisClient.Cmd("PING").Str()
if err != nil {
log.Fatal("healthCheck error: ", err)
}
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, res)
}
func createLockableCache(size int) lockableCache {
lruCache, err := lru.New(size)
if err != nil {
log.Fatal("Could not create 'redis' cache, err: ", err)
}
return lockableCache{lru: lruCache, lock: new(sync.RWMutex)}
}
func startExpiryDaemon(timeout int, ms time.Duration) {
expiryStop = make(chan bool)
go func() {
for {
select {
case <-expiryStop:
return
default:
time.Sleep(ms * time.Millisecond)
expireRedisCache(timeout)
}
}
}()
}
func stopExpiryDaemon() {
if expiryStop != nil {
expiryStop <- true
}
}
func expireRedisCache(ms int) {
redisCache.lock.Lock()
defer redisCache.lock.Unlock()
expiryTimeLimit := time.Now().UnixNano() - int64(ms*1000000)
//log.Printf("expireRedisCache expiryTimeLimit: %d timeLimit: %d\n", expiryTimeLimit, ms)
// These are oldest to newest
keys := redisCache.lru.Keys()
for _, key := range keys {
//log.Printf("expireRedisCache key: %s\n", key)
cached, _ := redisCache.lru.Get(key)
expiry := cached.(*valueStruct).expiryTime
// Short-circuit if we no longer need to expire entries
if expiry > expiryTimeLimit {
break
}
//log.Printf("expireRedisCache - removing key: %s expiry: %d limit: %d diff: %d\n", key, expiry, expiryTimeLimit, (expiry - expiryTimeLimit))
redisCache.lru.Remove(key)
}
}
func createRedisClient(addr string) (*redis.Client, error) {
return redis.DialTimeout("tcp", addr, 5*time.Second)
}
func createRouter() *mux.Router {
router := mux.NewRouter()
// Health Check
router.HandleFunc("/ping", healthCheck).Methods("GET")
// Redis GET
router.HandleFunc("/{key}", getRedis).Methods("GET")
return router
}
func getRedisValue(key string) (string, error) {
cached, found := redisCache.lru.Get(key)
if found {
val := cached.(*valueStruct).value
// Touch cache entry expiry timer
redisCache.lock.Lock()
redisCache.lru.Remove(key)
entry := &valueStruct{val, time.Now().UnixNano()}
redisCache.lru.Add(key, entry)
redisCache.lock.Unlock()
cacheHit++
return val, nil
}
cacheMiss++
val, err := redisClient.Cmd("GET", key).Str()
if err == redis.ErrRespNil {
return "", redis.ErrRespNil
}
if err != nil {
log.Printf("getRedisValue for key '%s', error: %s\n", key, err)
return "", err
}
// Update caching
entry := &valueStruct{val, time.Now().UnixNano()}
redisCache.lru.Add(key, entry)
return val, nil
}
func startListener(portStr string) error {
nlr, err := net.Listen("tcp", ":"+portStr)
if err != nil {
return err
}
defer nlr.Close()
log.Printf("Caching TCP redis proxy now listening on port " + portStr + "...\n")
for {
conn, err := nlr.Accept()
if err != nil {
log.Println("startListener - error accepting 'tcp' connection:", err)
}
log.Println("Accepted conn:", conn)
go handleRequest(conn)
}
}
var redisGet = regexp.MustCompile(`^\*\d+\r\n\$\d+\r\nGET\r\n\$\d+\r\n.*\r\n`)
func handleRequest(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 1024)
length, err := conn.Read(buf)
if err != nil {
log.Println("Error reading:", err.Error())
}
if redisGet.Match(buf) {
//log.Printf("Got redis request, length %d, '%s'\n", length, buf[:length])
keyToGet := string(unwrapRedisKey(buf[:length]))
val, _ := getRedisValue(keyToGet)
conn.Write([]byte(wrapRedisValue(val)))
return
}
log.Println("Got bad request: ", buf)
log.Println("Got bad request: ", string(buf))
}
func getRedis(w http.ResponseWriter, req *http.Request) {
// log.Println("Got request", req)
params := mux.Vars(req)
keyToGet := params["key"]
val, err := getRedisValue(keyToGet)
if err == redis.ErrRespNil {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, val)
}
func main() {
redisAddr, timeLimit, cacheSize, portStr, portType := getEnvironmentVariables()
log.Printf("Caching redis: %s, expiry=%d, cache size=%d, port=%s, type=%s\n", redisAddr, timeLimit, cacheSize, portStr, portType)
redisCache = createLockableCache(cacheSize)
startExpiryDaemon(timeLimit, 100)
defer stopExpiryDaemon()
var err error
redisClient, err = createRedisClient(redisAddr)
if err != nil {
log.Fatal("Error on 'redis' connection to '", redisAddr, "' error: ", err)
}
defer redisClient.Close()
if portType == "http" {
router := createRouter()
log.Printf("Caching HTTP redis proxy now listening on port " + portStr + "...\n")
log.Fatal(http.ListenAndServe(":"+portStr, router))
} else {
// TCP listener
err := startListener(portStr)
if err != nil {
log.Fatal("Error starting listener on port '", portStr, "' error: ", err)
}
}
}