github.com/godaddy-x/freego@v1.0.156/cache/local_cache.go (about) 1 package cache 2 3 import ( 4 "github.com/godaddy-x/freego/utils" 5 "github.com/patrickmn/go-cache" 6 "time" 7 ) 8 9 // 本地缓存管理器 10 type LocalMapManager struct { 11 CacheManager 12 c *cache.Cache 13 } 14 15 // a默认缓存时间/分钟 b默认校验数据间隔时间/分钟 16 func NewLocalCache(a, b int) Cache { 17 return new(LocalMapManager).NewCache(a, b) 18 } 19 20 // a默认缓存时间/分钟 b默认校验数据间隔时间/分钟 21 func (self *LocalMapManager) NewCache(a, b int) Cache { 22 c := cache.New(time.Duration(a)*time.Minute, time.Duration(b)*time.Minute) 23 return &LocalMapManager{c: c} 24 } 25 26 func (self *LocalMapManager) Get(key string, input interface{}) (interface{}, bool, error) { 27 v, b := self.c.Get(key) 28 if !b || v == nil { 29 return nil, false, nil 30 } 31 if input == nil { 32 return v, b, nil 33 } 34 return v, b, utils.JsonToAny(v, input) 35 } 36 37 func (self *LocalMapManager) GetInt64(key string) (int64, error) { 38 v, b := self.c.Get(key) 39 if !b || v == nil { 40 return 0, nil 41 } 42 if ret, err := utils.StrToInt64(utils.AnyToStr(v)); err != nil { 43 return 0, err 44 } else { 45 return ret, nil 46 } 47 } 48 49 func (self *LocalMapManager) GetFloat64(key string) (float64, error) { 50 v, b := self.c.Get(key) 51 if !b || v == nil { 52 return 0, nil 53 } 54 if ret, err := utils.StrToFloat(utils.AnyToStr(v)); err != nil { 55 return 0, err 56 } else { 57 return ret, nil 58 } 59 } 60 61 func (self *LocalMapManager) GetString(key string) (string, error) { 62 v, b := self.c.Get(key) 63 if !b || v == nil { 64 return "", nil 65 } 66 return utils.AnyToStr(v), nil 67 } 68 69 func (self *LocalMapManager) GetBytes(key string) ([]byte, error) { 70 v, b := self.c.Get(key) 71 if !b || v == nil { 72 return nil, nil 73 } 74 return v.([]byte), nil 75 } 76 77 func (self *LocalMapManager) GetBool(key string) (bool, error) { 78 v, b := self.c.Get(key) 79 if !b || v == nil { 80 return false, nil 81 } 82 return utils.StrToBool(utils.AnyToStr(v)) 83 } 84 85 func (self *LocalMapManager) Put(key string, input interface{}, expire ...int) error { 86 if expire != nil && len(expire) > 0 { 87 self.c.Set(key, input, time.Duration(expire[0])*time.Second) 88 } else { 89 self.c.SetDefault(key, input) 90 } 91 return nil 92 } 93 94 func (self *LocalMapManager) Del(key ...string) error { 95 if key != nil { 96 for _, v := range key { 97 self.c.Delete(v) 98 } 99 } 100 return nil 101 } 102 103 func (self *LocalMapManager) Exists(key string) (bool, error) { 104 _, b := self.c.Get(key) 105 return b, nil 106 } 107 108 // 数据量大时请慎用 109 func (self *LocalMapManager) Size(pattern ...string) (int, error) { 110 return self.c.ItemCount(), nil 111 } 112 113 func (self *LocalMapManager) Values(pattern ...string) ([]interface{}, error) { 114 return []interface{}{self.c.Items()}, nil 115 } 116 117 func (self *LocalMapManager) Flush() error { 118 self.c.Flush() 119 return nil 120 }