-
Notifications
You must be signed in to change notification settings - Fork 5
/
driver_lru.go
64 lines (55 loc) · 1.46 KB
/
driver_lru.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
package microcache
import (
"github.com/hashicorp/golang-lru"
)
// DriverLRU is a driver implementation using github.com/hashicorp/golang-lru
type DriverLRU struct {
RequestCache *lru.Cache
ResponseCache *lru.Cache
}
// NewDriverLRU returns the default LRU driver configuration.
// size determines the number of items in the cache.
// Memory usage should be considered when choosing the appropriate cache size.
// The amount of memory consumed by the driver will depend upon the response size.
// Roughly, memory = cacheSize * averageResponseSize / compression ratio
func NewDriverLRU(size int) DriverLRU {
// golang-lru segfaults when size is zero
if size < 1 {
size = 1
}
reqCache, _ := lru.New(size)
resCache, _ := lru.New(size)
return DriverLRU{
reqCache,
resCache,
}
}
func (c DriverLRU) SetRequestOpts(hash string, req RequestOpts) error {
c.RequestCache.Add(hash, req)
return nil
}
func (c DriverLRU) GetRequestOpts(hash string) (req RequestOpts) {
obj, success := c.RequestCache.Get(hash)
if success {
req = obj.(RequestOpts)
}
return req
}
func (c DriverLRU) Set(hash string, res Response) error {
c.ResponseCache.Add(hash, res)
return nil
}
func (c DriverLRU) Get(hash string) (res Response) {
obj, success := c.ResponseCache.Get(hash)
if success {
res = obj.(Response)
}
return res
}
func (c DriverLRU) Remove(hash string) error {
c.ResponseCache.Remove(hash)
return nil
}
func (c DriverLRU) GetSize() int {
return c.ResponseCache.Len()
}