gitee.com/sasukebo/go-micro/v4@v4.7.1/cache/default.go (about) 1 package cache 2 3 import ( 4 "context" 5 "sync" 6 "time" 7 ) 8 9 type memCache struct { 10 opts Options 11 sync.RWMutex 12 ctx context.Context 13 14 items map[string]Item 15 } 16 17 func (c *memCache) Context(ctx context.Context) Cache { 18 c.ctx = ctx 19 return c 20 } 21 22 func (c *memCache) Get(key string) (interface{}, time.Time, error) { 23 c.RWMutex.RLock() 24 defer c.RWMutex.RUnlock() 25 26 item, found := c.items[key] 27 if !found { 28 return nil, time.Time{}, ErrKeyNotFound 29 } 30 if item.Expired() { 31 return nil, time.Time{}, ErrItemExpired 32 } 33 34 return item.Value, time.Unix(0, item.Expiration), nil 35 } 36 37 func (c *memCache) Put(key string, val interface{}, d time.Duration) error { 38 var e int64 39 if d == DefaultExpiration { 40 d = c.opts.Expiration 41 } 42 if d > 0 { 43 e = time.Now().Add(d).UnixNano() 44 } 45 46 c.RWMutex.Lock() 47 defer c.RWMutex.Unlock() 48 49 c.items[key] = Item{ 50 Value: val, 51 Expiration: e, 52 } 53 54 return nil 55 } 56 57 func (c *memCache) Delete(key string) error { 58 c.RWMutex.Lock() 59 defer c.RWMutex.Unlock() 60 61 _, found := c.items[key] 62 if !found { 63 return ErrKeyNotFound 64 } 65 66 delete(c.items, key) 67 return nil 68 }