Junior — Middle
How can the content of the cache service be updated?
sobes.tech AI
Answer from AI
Updating the content of a cache service in Go usually involves several approaches:
-
Direct value update by key — if the cache is represented as a map or a specialized structure, you can simply replace the value by key.
-
Using TTL (Time To Live) — the cache automatically updates after the record's lifetime expires.
-
Invalidation mechanism — when data in the source changes, the cache is marked as stale and updated on the next request.
-
Background refresh — a goroutine periodically runs to update the cache on a schedule.
Example of simple cache update using a map and mutex for thread safety:
import "sync"
type Cache struct {
mu sync.Mutex
store map[string]string
}
func (c *Cache) Update(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.store[key] = value
}
func (c *Cache) Get(key string) (string, bool) {
c.mu.Lock()
defer c.mu.Unlock()
val, ok := c.store[key]
return val, ok
}
Thus, the update occurs through the Update method, which safely replaces the content by key.