forked from go-graphite/carbonapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
78 lines (58 loc) · 1.38 KB
/
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
package main
import (
"crypto/sha1"
"encoding/hex"
"time"
"github.com/bradfitz/gomemcache/memcache"
ecache "github.com/dgryski/go-expirecache"
)
type bytesCache interface {
get(k string) ([]byte, bool)
set(k string, v []byte, expire int32)
}
type nullCache struct{}
func (nullCache) get(string) ([]byte, bool) { return nil, false }
func (nullCache) set(string, []byte, int32) {}
type expireCache struct {
ec *ecache.Cache
}
func (ec expireCache) get(k string) ([]byte, bool) {
v, ok := ec.ec.Get(k)
if !ok {
return nil, false
}
return v.([]byte), true
}
func (ec expireCache) set(k string, v []byte, expire int32) {
ec.ec.Set(k, v, uint64(len(v)), expire)
}
type memcachedCache struct {
client *memcache.Client
}
func (m *memcachedCache) get(k string) ([]byte, bool) {
key := sha1.Sum([]byte(k))
hk := hex.EncodeToString(key[:])
done := make(chan bool, 1)
var err error
var item *memcache.Item
go func() {
item, err = m.client.Get(hk)
done <- true
}()
timeout := time.After(50 * time.Millisecond)
select {
case <-timeout:
Metrics.MemcacheTimeouts.Add(1)
return nil, false
case <-done:
}
if err != nil {
return nil, false
}
return item.Value, true
}
func (m *memcachedCache) set(k string, v []byte, expire int32) {
key := sha1.Sum([]byte(k))
hk := hex.EncodeToString(key[:])
go m.client.Set(&memcache.Item{Key: hk, Value: v, Expiration: expire})
}