github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/cache/operation.go (about) 1 package cache 2 3 import ( 4 "time" 5 ) 6 7 type optList interface { 8 AddItem(key string, value ...any) error 9 SetItem(key string, index int, value any) error 10 GetItem(key string) []any 11 GetItemByIndex(key string, index int) any 12 RemoveItem(key string, index int) error 13 } 14 15 func (c *Cache) getUnixNano() int64 { 16 de := c.defaultExpiration 17 var e int64 18 if de != -1 { 19 e = time.Now().Add(de).UnixNano() 20 } 21 return e 22 } 23 24 //Set Add an item to the cache,replacing any existing item. 25 //note key is primary key 26 func (c *Cache) Set(key string, value any) error { 27 e := c.getUnixNano() 28 c.mu.Lock() 29 defer c.mu.Unlock() 30 c.items[key] = Item{ 31 Data: value, 32 Ttl: e, 33 } 34 return nil 35 } 36 37 //Get an item from the cache.Returns the item or nil, and a bool indicating 38 // whether the key was found 39 func (c *Cache) Get(key string) (any, bool) { 40 c.mu.Lock() 41 defer c.mu.Unlock() 42 if item, found := c.items[key]; !found { 43 return nil, found 44 } else { 45 //check item has expired 46 if item.Ttl > 0 && time.Now().UnixNano() > item.Ttl { 47 return nil, found 48 } 49 return item.Data, true 50 } 51 } 52 53 func (c *Cache) Remove(key string) { 54 c.mu.Lock() 55 defer c.mu.Unlock() 56 if _, found := c.items[key]; found { 57 delete(c.items, key) 58 return 59 } 60 } 61 62 func (c *Cache) Clean() { 63 c.mu.Lock() 64 defer c.mu.Unlock() 65 for k := range c.items { 66 delete(c.items, k) 67 } 68 } 69 70 func (c *Cache) Cap() int { 71 c.mu.Lock() 72 defer c.mu.Unlock() 73 ci := c.items 74 return len(ci) 75 }