go-micro.dev/v5@v5.12.0/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  type Cache interface {
    26  	// Get gets a cached value by key.
    27  	Get(ctx context.Context, key string) (interface{}, time.Time, error)
    28  	// Put stores a key-value pair into cache.
    29  	Put(ctx context.Context, key string, val interface{}, d time.Duration) error
    30  	// Delete removes a key from cache.
    31  	Delete(ctx context.Context, key string) error
    32  	// String returns the name of the implementation.
    33  	String() string
    34  }
    35  
    36  // Item represents an item stored in the cache.
    37  type Item struct {
    38  	Value      interface{}
    39  	Expiration int64
    40  }
    41  
    42  // Expired returns true if the item has expired.
    43  func (i *Item) Expired() bool {
    44  	if i.Expiration == 0 {
    45  		return false
    46  	}
    47  
    48  	return time.Now().UnixNano() > i.Expiration
    49  }
    50  
    51  // NewCache returns a new cache.
    52  func NewCache(opts ...Option) Cache {
    53  	options := NewOptions(opts...)
    54  	items := make(map[string]Item)
    55  
    56  	if len(options.Items) > 0 {
    57  		items = options.Items
    58  	}
    59  
    60  	return &memCache{
    61  		opts:  options,
    62  		items: items,
    63  	}
    64  }