gitee.com/woood2/luca@v1.0.4/internal/cache/local.go (about) 1 package cache 2 3 import ( 4 "sync" 5 "time" 6 ) 7 8 func Local() Cache { 9 return localCache 10 } 11 12 var localCache = &LocalCache{ 13 Protector: Protector{ 14 lock: sync.Mutex{}, 15 apply: make(map[string]chan struct{}), 16 }, 17 dict: sync.Map{}, 18 } 19 20 type LocalCache struct { 21 Protector 22 MissHolder 23 dict sync.Map 24 } 25 26 func (c *LocalCache) Get(k string, p interface{}) error { 27 res, ok := c.dict.Load(k) 28 if !ok { 29 return Miss 30 } 31 ttl := res.(*item).ttl 32 if time.Now().After(ttl) { 33 return Miss 34 } 35 Deserialize(res.(*item).value, p) 36 return nil 37 } 38 39 func (c *LocalCache) Set(k string, v interface{}, d time.Duration) error { 40 i := &item{ 41 key: k, 42 value: Serialize(v), 43 ttl: time.Now().Add(d), 44 } 45 c.dict.Store(k, i) 46 return nil 47 } 48 49 type item struct { 50 key string 51 value string 52 ttl time.Time 53 }