Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Last active June 4, 2024 08:01
Show Gist options
  • Save alexedwards/af9bc1a31964342c199e9a832ab91b77 to your computer and use it in GitHub Desktop.
Save alexedwards/af9bc1a31964342c199e9a832ab91b77 to your computer and use it in GitHub Desktop.
Generic in-memory cache implementation in Go
package cache
import (
"sync"
"time"
)
// Cache is a basic in-memory key-value cache implementation.
type Cache[K comparable, V any] struct {
items map[K]V // The map storing key-value pairs.
mu sync.Mutex // Mutex for controlling concurrent access to the cache.
}
// New creates a new Cache instance.
func New[K comparable, V any]() *Cache[K, V] {
return &Cache[K, V]{
items: make(map[K]V),
}
}
// Set adds or updates a key-value pair in the cache.
func (c *Cache[K, V]) Set(key K, value V) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = value
}
// Get retrieves the value associated with the given key from the cache. The bool
// return value will be false if no matching key is found, and true otherwise.
func (c *Cache[K, V]) Get(key K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
value, found := c.items[key]
return value, found
}
// Remove deletes the key-value pair with the specified key from the cache.
func (c *Cache[K, V]) Remove(key K) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.items, key)
}
// Pop removes and returns the value associated with the specified key from the cache.
func (c *Cache[K, V]) Pop(key K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
value, found := c.items[key]
// If the key is found, delete the key-value pair from the cache.
if found {
delete(c.items, key)
}
return value, found
}
package cache
import (
"sync"
"time"
)
// item represents a cache item with a value and an expiration time.
type item[V any] struct {
value V
expiry time.Time
}
// isExpired checks if the cache item has expired.
func (i item[V]) isExpired() bool {
return time.Now().After(i.expiry)
}
// TTLCache is a generic cache implementation with support for time-to-live
// (TTL) expiration.
type TTLCache[K comparable, V any] struct {
items map[K]item[V] // The map storing cache items.
mu sync.Mutex // Mutex for controlling concurrent access to the cache.
}
// NewTTL creates a new TTLCache instance and starts a goroutine to periodically
// remove expired items every 5 seconds.
func NewTTL[K comparable, V any]() *TTLCache[K, V] {
c := &TTLCache[K, V]{
items: make(map[K]item[V]),
}
go func() {
for range time.Tick(5 * time.Second) {
c.mu.Lock()
// Iterate over the cache items and delete expired ones.
for key, item := range c.items {
if item.isExpired() {
delete(c.items, key)
}
}
c.mu.Unlock()
}
}()
return c
}
// Set adds a new item to the cache with the specified key, value, and
// time-to-live (TTL).
func (c *TTLCache[K, V]) Set(key K, value V, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = item[V]{
value: value,
expiry: time.Now().Add(ttl),
}
}
// Get retrieves the value associated with the given key from the cache.
func (c *TTLCache[K, V]) Get(key K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
item, found := c.items[key]
if !found {
// If the key is not found, return the zero value for V and false.
return item.value, false
}
if item.isExpired() {
// If the item has expired, remove it from the cache and return the
// value and false.
delete(c.items, key)
return item.value, false
}
// Otherwise return the value and true.
return item.value, true
}
// Remove removes the item with the specified key from the cache.
func (c *TTLCache[K, V]) Remove(key K) {
c.mu.Lock()
defer c.mu.Unlock()
// Delete the item with the given key from the cache.
delete(c.items, key)
}
// Pop removes and returns the item with the specified key from the cache.
func (c *TTLCache[K, V]) Pop(key K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
item, found := c.items[key]
if !found {
// If the key is not found, return the zero value for V and false.
return item.value, false
}
// If the key is found, delete the item from the cache.
delete(c.items, key)
if item.isExpired() {
// If the item has expired, return the value and false.
return item.value, false
}
// Otherwise return the value and true.
return item.value, true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment