go-micro.dev/v5@v5.12.0/cache/memory.go (about)

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