github.com/iotexproject/iotex-core@v1.14.1-rc1/api/read_cache.go (about) 1 package api 2 3 import ( 4 "encoding/json" 5 6 "github.com/iotexproject/go-pkgs/cache/ttl" 7 "github.com/iotexproject/go-pkgs/hash" 8 "go.uber.org/zap" 9 10 "github.com/iotexproject/iotex-core/pkg/log" 11 ) 12 13 type ( 14 // ReadKey represents a read key 15 ReadKey struct { 16 Name string `json:"name,omitempty"` 17 Height string `json:"height,omitempty"` 18 Method []byte `json:"method,omitempty"` 19 Args [][]byte `json:"args,omitempty"` 20 } 21 22 // ReadCache stores read results 23 ReadCache struct { 24 total, hit int 25 c *ttl.Cache 26 } 27 ) 28 29 // Hash returns the hash of key's json string 30 func (k *ReadKey) Hash() hash.Hash160 { 31 b, _ := json.Marshal(k) 32 return hash.Hash160b(b) 33 } 34 35 // NewReadCache returns a new read cache 36 func NewReadCache() *ReadCache { 37 c, _ := ttl.NewCache() 38 return &ReadCache{ 39 c: c, 40 } 41 } 42 43 // Get reads according to key 44 func (rc *ReadCache) Get(key hash.Hash160) ([]byte, bool) { 45 rc.total++ 46 d, ok := rc.c.Get(key) 47 if !ok { 48 return nil, false 49 } 50 rc.hit++ 51 if rc.hit%100 == 0 { 52 log.Logger("api").Info("API cache hit", zap.Int("total", rc.total), zap.Int("hit", rc.hit)) 53 } 54 return d.([]byte), true 55 } 56 57 // Put writes according to key 58 func (rc *ReadCache) Put(key hash.Hash160, value []byte) { 59 rc.c.Set(key, value) 60 } 61 62 // Clear clears the cache 63 func (rc *ReadCache) Clear() { 64 rc.c.Reset() 65 }