47 lines
801 B
Go
47 lines
801 B
Go
package store
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type HotCache struct {
|
|
mu sync.RWMutex
|
|
entries map[string]cacheEntry
|
|
ttl time.Duration
|
|
}
|
|
|
|
type cacheEntry struct {
|
|
value any
|
|
expiresAt time.Time
|
|
}
|
|
|
|
func NewHotCache(ttl time.Duration) *HotCache {
|
|
return &HotCache{
|
|
entries: make(map[string]cacheEntry),
|
|
ttl: ttl,
|
|
}
|
|
}
|
|
|
|
func (c *HotCache) Get(key string) (any, bool) {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
e, ok := c.entries[key]
|
|
if !ok || time.Now().After(e.expiresAt) {
|
|
return nil, false
|
|
}
|
|
return e.value, true
|
|
}
|
|
|
|
func (c *HotCache) Set(key string, value any) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
c.entries[key] = cacheEntry{value: value, expiresAt: time.Now().Add(c.ttl)}
|
|
}
|
|
|
|
func (c *HotCache) Delete(key string) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
delete(c.entries, key)
|
|
}
|