forked from kevburnsjr/microcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver_arc.go
69 lines (60 loc) · 1.77 KB
/
driver_arc.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
package microcache
import (
"github.com/hashicorp/golang-lru"
)
// DriverARC is a driver implementation using github.com/hashicorp/golang-lru
// ARCCache is a thread-safe fixed size Adaptive Replacement Cache (ARC).
// It requires more ram and cpu than straight LRO but can be more efficient
// https://godoc.org/github.com/hashicorp/golang-lru#ARCCache
type DriverARC struct {
RequestCache *lru.ARCCache
ResponseCache *lru.ARCCache
}
// NewDriverARC returns an ARC driver.
// 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
// ARC caches have additional CPU and memory overhead when compared with LRU
// ARC does not support eviction monitoring
func NewDriverARC(size int) DriverARC {
// golang-lru segfaults when size is zero
if size < 1 {
size = 1
}
reqCache, _ := lru.NewARC(size)
resCache, _ := lru.NewARC(size)
return DriverARC{
reqCache,
resCache,
}
}
func (c DriverARC) SetRequestOpts(hash string, req RequestOpts) error {
c.RequestCache.Add(hash, req)
return nil
}
func (c DriverARC) GetRequestOpts(hash string) (req RequestOpts) {
obj, success := c.RequestCache.Get(hash)
if success {
req = obj.(RequestOpts)
}
return req
}
func (c DriverARC) Set(hash string, res Response) error {
c.ResponseCache.Add(hash, res)
return nil
}
func (c DriverARC) Get(hash string) (res Response) {
obj, success := c.ResponseCache.Get(hash)
if success {
res = obj.(Response)
}
return res
}
func (c DriverARC) Remove(hash string) error {
c.ResponseCache.Remove(hash)
return nil
}
func (c DriverARC) GetSize() int {
return c.ResponseCache.Len()
}