MCPcopy Create free account
hub / github.com/PacktPublishing/System-Programming-Essentials-with-Go / Set

Method Set

ch13/cache.go:39–60  ·  view source on GitHub ↗

Set adds or updates a cache entry with the specified key, value, and TTL

(key, value string, ttl time.Duration)

Source from the content-addressed store, hash-verified

37
38// Set adds or updates a cache entry with the specified key, value, and TTL
39func (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
63func (c *Cache) Get(key string) (string, bool) {

Callers 8

TestCacheEvictsLRUFunction · 0.95
TestCacheConcurrencyFunction · 0.95
SetHandlerMethod · 0.80
replicateSetMethod · 0.80

Calls 1

evictLRUMethod · 0.95

Tested by 6

TestCacheEvictsLRUFunction · 0.76
TestCacheConcurrencyFunction · 0.76