gitee.com/sasukebo/go-micro/v4@v4.7.1/cache/cache.go (about) 1 package cache 2 3 import ( 4 "context" 5 "errors" 6 "time" 7 ) 8 9 var ( 10 // DefaultCache is the default cache. 11 DefaultCache Cache = NewCache() 12 // DefaultExpiration is the default duration for items stored in 13 // the cache to expire. 14 DefaultExpiration time.Duration = 0 15 16 // ErrItemExpired is returned in Cache.Get when the item found in the cache 17 // has expired. 18 ErrItemExpired error = errors.New("item has expired") 19 // ErrKeyNotFound is returned in Cache.Get and Cache.Delete when the 20 // provided key could not be found in cache. 21 ErrKeyNotFound error = errors.New("key not found in cache") 22 ) 23 24 // Cache is the interface that wraps the cache. 25 // 26 // Context specifies the context for the cache. 27 // Get gets a cached value by key. 28 // Put stores a key-value pair into cache. 29 // Delete removes a key from cache. 30 type Cache interface { 31 Context(ctx context.Context) Cache 32 Get(key string) (interface{}, time.Time, error) 33 Put(key string, val interface{}, d time.Duration) error 34 Delete(key string) error 35 } 36 37 // Item represents an item stored in the cache. 38 type Item struct { 39 Value interface{} 40 Expiration int64 41 } 42 43 // Expired returns true if the item has expired. 44 func (i *Item) Expired() bool { 45 if i.Expiration == 0 { 46 return false 47 } 48 49 return time.Now().UnixNano() > i.Expiration 50 } 51 52 // NewCache returns a new cache. 53 func NewCache(opts ...Option) Cache { 54 options := NewOptions(opts...) 55 items := make(map[string]Item) 56 57 if len(options.Items) > 0 { 58 items = options.Items 59 } 60 61 return &memCache{ 62 opts: options, 63 items: items, 64 } 65 }