Principal
É necessário escrever uma biblioteca simples de cache em memória. tipo Cache interface { Set(k, v string) Get(k string) (v string, ok bool) }
sobes.tech IA
Resposta da IA
A seguir, um exemplo simples de implementação de cache em memória em Go, que corresponde à interface:
type Cache interface {
Set(k, v string)
Get(k string) (v string, ok bool)
}
type SimpleCache struct {
data map[string]string
mu sync.RWMutex
}
func NewSimpleCache() *SimpleCache {
return &SimpleCache{
data: make(map[string]string),
}
}
func (c *SimpleCache) Set(k, v string) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[k] = v
}
func (c *SimpleCache) Get(k string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok := c.data[k]
return v, ok
}
Aqui, um mutex é utilizado para acesso seguro ao mapa. Este cache armazena dados na memória até à reinicialização da aplicação.