Use a LRU for the cache

This commit is contained in:
Frank Denis 2018-01-10 19:02:43 +01:00
parent 8e73bb4a2c
commit 132add7955
1 changed files with 8 additions and 13 deletions

View File

@ -4,10 +4,10 @@ import (
"crypto/sha512" "crypto/sha512"
"encoding/binary" "encoding/binary"
"errors" "errors"
"math/rand"
"sync" "sync"
"time" "time"
lru "github.com/hashicorp/golang-lru"
"github.com/miekg/dns" "github.com/miekg/dns"
) )
@ -191,7 +191,7 @@ type CachedResponse struct {
type CachedResponses struct { type CachedResponses struct {
sync.RWMutex sync.RWMutex
cache map[[32]byte]CachedResponse cache *lru.ARCCache
} }
var cachedResponses CachedResponses var cachedResponses CachedResponses
@ -226,18 +226,12 @@ func (plugin *PluginCacheResponse) Eval(pluginsState *PluginsState, msg *dns.Msg
plugin.cachedResponses.Lock() plugin.cachedResponses.Lock()
defer plugin.cachedResponses.Unlock() defer plugin.cachedResponses.Unlock()
if plugin.cachedResponses.cache == nil { if plugin.cachedResponses.cache == nil {
plugin.cachedResponses.cache = make(map[[32]byte]CachedResponse) plugin.cachedResponses.cache, err = lru.NewARC(1000)
} if err != nil {
if len(plugin.cachedResponses.cache) > 1000 { return err
z := byte(rand.Uint32())
for k := range plugin.cachedResponses.cache {
delete(plugin.cachedResponses.cache, k)
if k[0] == z {
break
} }
} }
} plugin.cachedResponses.cache.Add(cacheKey, cachedResponse)
plugin.cachedResponses.cache[cacheKey] = cachedResponse
return nil return nil
} }
@ -265,10 +259,11 @@ func (plugin *PluginCache) Eval(pluginsState *PluginsState, msg *dns.Msg) error
if plugin.cachedResponses.cache == nil { if plugin.cachedResponses.cache == nil {
return nil return nil
} }
cached, ok := plugin.cachedResponses.cache[cacheKey] cached_any, ok := plugin.cachedResponses.cache.Get(cacheKey)
if !ok { if !ok {
return nil return nil
} }
cached := cached_any.(CachedResponse)
if time.Now().After(cached.expiration) { if time.Now().After(cached.expiration) {
return nil return nil
} }