-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcacheController.go
62 lines (47 loc) · 1.5 KB
/
cacheController.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
package main
import (
"math/rand"
"time"
types "github.com/distributeddesigns/shared_types"
"github.com/garyburd/redigo/redis"
)
func getCachedQuote(stock string) (types.Quote, bool) {
conn := redisPool.Get()
defer conn.Close()
quoteKey := makeQuoteKey(stock)
r, err := redis.String(conn.Do("GET", quoteKey))
if err == redis.ErrNil {
consoleLog.Debugf(" [x] Cache miss: %s", quoteKey)
return types.Quote{}, false
} else if err != nil {
failOnError(err, "Could not retrieve quote from redis")
}
quote, err := types.ParseQuote(r)
failOnError(err, "Could not parse quote from redis value")
return quote, true
}
func updateCachedQuote(q types.Quote) {
quoteAge := time.Now().Unix() - q.Timestamp.Unix()
ttl := config.QuotePolicy.BaseTTL - rand.Intn(config.QuotePolicy.BackoffTTL) - int(quoteAge)
if ttl <= 0 {
consoleLog.Debugf("Invalid ttl: %d. Not caching.", ttl)
return
}
conn := redisPool.Get()
defer conn.Close()
quoteKey := makeQuoteKey(q.Stock)
serializedQuote := q.ToCSV()
_, err := conn.Do("SETEX", quoteKey, ttl, serializedQuote)
failOnError(err, "Could not update quote in redis")
consoleLog.Debugf("Updated: %s:%s", quoteKey, serializedQuote)
consoleLog.Debugf("%s will expire in %d sec", quoteKey, ttl)
}
func makeQuoteKey(stock string) string {
// Truncate the stock to three characters to match the behavior
// of the quoteserver.
// TODO: Quote{} should enforce the size limit?
if len(stock) > 3 {
stock = stock[:3]
}
return config.Redis.KeyPrefix + "quotes:" + stock
}