-
Notifications
You must be signed in to change notification settings - Fork 180
/
lru.go
61 lines (52 loc) · 1.15 KB
/
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
package state
import (
"errors"
"sync"
"github.com/spf13/viper"
"github.com/tendermint/go-amino"
lru "github.com/hashicorp/golang-lru"
)
//the default lru cache size is 1kw, that means the max memory size we needs is (32 + 32 + 4) * 10000000, about 700MB
var (
defaultLruSize int = 10000000
gStateLru *lru.Cache
once sync.Once
)
//redefine fast-query to avoid cycle package import
const FlagFastQuery = "fast-query"
func isWatcherEnabled() bool {
return viper.GetBool(FlagFastQuery)
}
func InstanceOfStateLru() *lru.Cache {
once.Do(func() {
if isWatcherEnabled() {
var e error = nil
gStateLru, e = lru.New(defaultLruSize)
if e != nil {
panic(errors.New("Failed to call InstanceOfStateLru cause :" + e.Error()))
}
}
})
return gStateLru
}
func GetStateFromLru(key []byte) []byte {
cache := InstanceOfStateLru()
if cache == nil {
return nil
}
value, ok := cache.Get(amino.BytesToStr(key))
if ok {
ret, ok := value.([]byte)
if ok {
return ret
}
}
return nil
}
func SetStateToLru(key []byte, value []byte) {
cache := InstanceOfStateLru()
if cache == nil {
return
}
cache.Add(amino.BytesToStr(key), value)
}