Last active
February 12, 2025 15:18
-
-
Save wjkoh/fbd491e2069e51ffefb0e4b9818c5ec2 to your computer and use it in GitHub Desktop.
Go: A Simple TTL Cache Using time.AfterFunc()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cache | |
import ( | |
"sync" | |
"time" | |
) | |
type Cache[K comparable, V any] interface { | |
Set(K, V) | |
Get(K) (V, bool) | |
Remove(K) | |
} | |
type ttlCache[K comparable, V any] struct { | |
items map[K]V | |
ttl time.Duration | |
mu sync.Mutex | |
} | |
func NewTtl[K comparable, V any](ttl time.Duration) Cache[K, V] { | |
return &ttlCache[K, V]{ | |
items: make(map[K]V), | |
ttl: ttl, | |
} | |
} | |
func (c *ttlCache[K, V]) Set(key K, value V) { | |
c.mu.Lock() | |
defer c.mu.Unlock() | |
c.items[key] = value | |
if c.ttl > 0 { | |
time.AfterFunc(c.ttl, func() { c.Remove(key) }) | |
} | |
} | |
func (c *ttlCache[K, V]) Get(key K) (V, bool) { | |
c.mu.Lock() | |
defer c.mu.Unlock() | |
v, ok := c.items[key] | |
return v, ok | |
} | |
func (c *ttlCache[K, V]) Remove(key K) { | |
c.mu.Lock() | |
defer c.mu.Unlock() | |
delete(c.items, key) | |
} |
Author
wjkoh
commented
Feb 12, 2025
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment