Middle+
Have you worked with caching? If yes, what kind?
sobes.tech AI
Answer from AI
Yes, in Go projects I have used caching to improve performance and reduce database load. Mainly worked with:
- Built-in in-memory cache using map and sync.RWMutex for thread safety.
- Redis as an external cache for distributed systems, using the go-redis library.
Example of a simple in-memory cache:
package main
import (
"sync"
"time"
)
type Cache struct {
mu sync.RWMutex
store map[string]string
}
func NewCache() *Cache {
return &Cache{store: make(map[string]string)}
}
func (c *Cache) Get(key string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
val, ok := c.store[key]
return val, ok
}
func (c *Cache) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.store[key] = value
}
func main() {
cache := NewCache()
cache.Set("user_1", "John Doe")
if val, ok := cache.Get("user_1"); ok {
println(val) // John Doe
}
// You can add logic for time-based clearing, etc.
}
This approach helps reduce the number of requests to slow data sources and speeds up service response.