refactor memory cache into map[string]dns.Msg

This commit is contained in:
kenshin 2013-07-24 19:01:31 +08:00
parent 51be27eee9
commit 0dfc4bf100
2 changed files with 17 additions and 18 deletions

View File

@ -47,24 +47,24 @@ type Cache interface {
}
type MemoryCache struct {
backend map[string]string
backend map[string]*dns.Msg
serializer *JsonSerializer
expire time.Duration
maxcount int
}
func (c *MemoryCache) Get(key string) (*dns.Msg, error) {
fmt.Println(c.backend)
data, ok := c.backend[key]
mesg, ok := c.backend[key]
if !ok {
return nil, KeyNotFound{key}
}
mesg := new(dns.Msg)
if err := c.serializer.Loads([]byte(data), &mesg); err != nil {
fmt.Println(err)
return nil, SerializerError{}
}
// mesg := new(dns.Msg)
// if err := c.serializer.Loads([]byte(data), &mesg); err != nil {
// fmt.Println(err)
// return nil, SerializerError{}
// }
return mesg, nil
}
@ -73,13 +73,14 @@ func (c *MemoryCache) Set(key string, mesg *dns.Msg) error {
if c.Full() && !c.Exists(key) {
return CacheIsFull{}
}
data, err := c.serializer.Dumps(mesg)
// data, err := c.serializer.Dumps(mesg)
if err != nil {
return SerializerError{}
}
// if err != nil {
// return SerializerError{}
// }
c.backend[key] = string(data)
// c.backend[key] = string(data)
c.backend[key] = mesg
return nil
}

View File

@ -2,8 +2,6 @@ package main
import (
"github.com/miekg/dns"
// "log"
"fmt"
)
type Question struct {
@ -44,14 +42,14 @@ func NewHandler() *GODNSHandler {
switch cacheConfig.Backend {
case "memory":
cache = &MemoryCache{
backend: make(map[string]string),
backend: make(map[string]*dns.Msg),
serializer: new(JsonSerializer),
expire: cacheConfig.Expire,
maxcount: cacheConfig.Maxcount,
}
case "redis":
cache = &MemoryCache{
backend: make(map[string]string),
backend: make(map[string]*dns.Msg),
serializer: new(JsonSerializer),
expire: cacheConfig.Expire,
maxcount: cacheConfig.Maxcount,
@ -71,7 +69,6 @@ func (h *GODNSHandler) do(net string, w dns.ResponseWriter, req *dns.Msg) {
Debug("Question: %s", Q.String())
key := KeyGen(Q)
fmt.Println(key)
// Only query cache when qtype == 'A' , qclass == 'IN'
if q.Qtype == dns.TypeA && q.Qclass == dns.ClassINET {
mesg, err := h.cache.Get(key)
@ -79,6 +76,7 @@ func (h *GODNSHandler) do(net string, w dns.ResponseWriter, req *dns.Msg) {
Debug("%s didn't hit cache: %s", Q.String(), err)
} else {
Debug("%s hit cache", Q.String())
mesg.Id = req.Id
w.WriteMsg(mesg)
return
}