Improve caching, move mutex to the cache implementation
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user