Thread-safe memorijski cache u Go s TTL-om i mutexom za učinkovito upravljanje privremenim podacima i automatsko uklanjanje isteklih stavki.
package main
import (
"fmt"
"sync"
"time"
)
// cacheItem predstavlja jedan element u cacheu s vrijednošću i vremenom isteka
type cacheItem struct {
value interface{} // pohranjena vrijednost
expiration time.Time // vrijeme kada element istječe
}
// Cache je thread-safe struktura koja pohranjuje elemente s TTL-om
// i automatski uklanja istekle
//
// Cache koristi mutex za sinkronizaciju konkurentnog pristupa
// i ticker za periodično čišćenje isteklih elemenata.
type Cache struct {
items map[string]cacheItem
mu sync.RWMutex
tick *time.Ticker
quit chan struct{}
}
// NewCache stvara novi cache s određenim intervalom čišćenja
// cleanupInterval definira koliko često se uklanjaju istekli elementi
func NewCache(cleanupInterval time.Duration) *Cache {
c := &Cache{
items: make(map[string]cacheItem),
mu: sync.RWMutex{},
tick: time.NewTicker(cleanupInterval),
quit: make(chan struct{}),
}
go c.cleanupLoop()
return c
}
// Set umeće ili ažurira element u cacheu s ključem, vrijednošću i TTL-om
// ttl je vrijeme trajanja elementa nakon kojeg se smatra isteklim
func (c *Cache) Set(key string, value interface{}, ttl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = cacheItem{
value: value,
expiration: time.Now().Add(ttl),
}
}
// Get vraća vrijednost povezanu s ključem ako postoji i nije istekla
// Druga boolean vrijednost označava je li vrijednost pronađena i valjana
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock()
item, found := c.items[key]
c.mu.RUnlock()
if !found {
return nil, false
}
// Provjerava je li element istekao
if time.Now().After(item.expiration) {
// Uklanja istekli element
c.mu.Lock()
delete(c.items, key)
c.mu.Unlock()
return nil, false
}
return item.value, true
}
// Delete uklanja element iz cachea
func (c *Cache) Delete(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.items, key)
}
// Clear potpuno prazni cache
func (c *Cache) Clear() {
c.mu.Lock()
defer c.mu.Unlock()
c.items = make(map[string]cacheItem)
}
// cleanupLoop periodički uklanja istekle elemente
func (c *Cache) cleanupLoop() {
for {
select {
case <-c.tick.C:
c.deleteExpired()
case <-c.quit:
c.tick.Stop()
return
}
}
}
// deleteExpired uklanja sve istekle elemente iz cachea
func (c *Cache) deleteExpired() {
c.mu.Lock()
defer c.mu.Unlock()
now := time.Now()
for k, item := range c.items {
if now.After(item.expiration) {
delete(c.items, k)
}
}
}
// Close zaustavlja ticker i čisti resurse cachea
func (c *Cache) Close() {
close(c.quit)
}
func main() {
// Kreiramo cache s čišćenjem svakih 5 sekundi
cache := NewCache(5 * time.Second)
defer cache.Close()
// Umetnemo element s TTL-om od 10 sekundi
cache.Set("chiave1", "valore1", 10*time.Second)
// Odmah dohvatimo vrijednost
val, ok := cache.Get("chiave1")
if ok {
fmt.Println("Vrijednost pronađena:", val)
} else {
fmt.Println("Vrijednost nije pronađena ili je istekla")
}
// Čekamo 11 sekundi da element istekne
time.Sleep(11 * time.Second)
// Pokušavamo ponovno dohvatiti
val, ok = cache.Get("chiave1")
if ok {
fmt.Println("Vrijednost pronađena:", val)
} else {
fmt.Println("Vrijednost nije pronađena ili je istekla")
}
}