Improve caching, move mutex to the cache implementation

This commit is contained in:
2023-08-24 23:53:52 +03:00
parent 49c962e13c
commit acb9f97806
4 changed files with 42 additions and 28 deletions

View File

@@ -1,11 +1,42 @@
package inmemorycache
type Cache map[uint64][]string
import (
"sync"
)
func (c Cache) Get(id uint64) []string {
return c[id]
func NewCache() *Cache {
return &Cache{cache: map[uint64][]string{}}
}
func (c Cache) Append(id uint64, ip string) {
c[id] = append(c[id], ip)
type Cache struct {
cache map[uint64][]string
mu sync.RWMutex
}
func (c *Cache) Get(id uint64) []string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.cache[id]
}
func (c *Cache) Append(id uint64, ip string) {
c.mu.Lock()
defer c.mu.Unlock()
if ips := c.cache[id]; len(ips) == 0 {
c.cache[id] = append(c.cache[id], ip)
return
}
for _, s := range c.cache[id] {
if s == ip {
return
}
}
c.cache[id] = append(c.cache[id], ip)
return
}