Set adds or updates a cache entry with the specified key, value, and TTL
(key, value string, ttl time.Duration)
| 37 | |
| 38 | // Set adds or updates a cache entry with the specified key, value, and TTL |
| 39 | func (c *Cache) Set(key, value string, ttl time.Duration) { |
| 40 | c.mu.Lock() |
| 41 | defer c.mu.Unlock() |
| 42 | |
| 43 | // Remove the old value if it exists |
| 44 | if elem, found := c.items[key]; found { |
| 45 | c.eviction.Remove(elem) |
| 46 | delete(c.items, key) |
| 47 | } |
| 48 | |
| 49 | // Evict the least recently used item if the cache is at capacity |
| 50 | if c.eviction.Len() >= c.capacity { |
| 51 | c.evictLRU() |
| 52 | } |
| 53 | |
| 54 | item := CacheItem{ |
| 55 | Value: value, |
| 56 | ExpiryTime: time.Now().Add(ttl), |
| 57 | } |
| 58 | elem := c.eviction.PushFront(&entry{key, item}) |
| 59 | c.items[key] = elem |
| 60 | } |
| 61 | |
| 62 | // Get retrieves a cache entry by its key. It returns the value and a boolean indicating whether the key was found |
| 63 | func (c *Cache) Get(key string) (string, bool) { |