Junior — Middle
Can you give an example of an approach to organizing data caching in a system?
sobes.tech AI
Answer from AI
In Go, built-in data structures like map with additional logic for managing cache lifetime (TTL) are often used for data caching. One simple approach is to create a structure that stores data and its creation time, and upon request, check whether the data has expired.
Example of a simple cache with TTL:
package main
import (
"fmt"
"sync"
"time"
)
type cacheItem struct {
value interface{}
expiration time.Time
}
type Cache struct {
items map[string]cacheItem
mu sync.RWMutex
ttl time.Duration
}
func NewCache(ttl time.Duration) *Cache {
return &Cache{
items: make(map[string]cacheItem),
ttl: ttl,
}
}
func (c *Cache) Set(key string, value interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = cacheItem{
value: value,
expiration: time.Now().Add(c.ttl),
}
}
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
item, found := c.items[key]
if !found || time.Now().After(item.expiration) {
return nil, false
}
return item.value, true
}
func main() {
cache := NewCache(5 * time.Minute)
cache.Set("user_1", "John Doe")
if val, ok := cache.Get("user_1"); ok {
fmt.Println("Cached value:", val)
} else {
fmt.Println("Value not found or expired")
}
}
This approach is suitable for simple cases. For more complex systems, specialized libraries or external caches (Redis, Memcached) are used.