Senior
What is cached? Only reference data?
sobes.tech AI
Answer from AI
Caching was applied not only to reference data but also to other types of data that are frequently requested and rarely changed. For example:
- Results of complex calculations or aggregations to avoid recalculating on each request.
- Responses from external APIs to reduce load and latency.
- User sessions and authentication tokens for quick access.
In Go, I usually use built-in data structures, such as a map with a mutex for thread safety, or third-party caching libraries (e.g., groupcache, ristretto) that provide TTL, automatic removal of stale data, and efficient memory management.
Example of a simple cache with TTL:
import (
"sync"
"time"
)
type CacheItem struct {
Value interface{}
Expiration int64
}
type Cache struct {
items map[string]CacheItem
mu sync.RWMutex
}
func (c *Cache) Set(key string, value interface{}, duration time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = CacheItem{
Value: value,
Expiration: time.Now().Add(duration).UnixNano(),
}
}
func (c *Cache) Get(key string) (interface{}, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
item, found := c.items[key]
if !found || time.Now().UnixNano() > item.Expiration {
return nil, false
}
return item.Value, true
}