add option for enable/disable cache

dns
Dingjun 8 years ago
parent 0eceb283e8
commit fbb898dde9

@ -43,6 +43,7 @@ type Rule struct {
} }
type cfg struct { type cfg struct {
EnableCache bool `json:"enable_cache"`
Listen []string `json:"listen"` Listen []string `json:"listen"`
User string `json:"user"` User string `json:"user"`
Group string `json:"group"` Group string `json:"group"`

@ -5,6 +5,7 @@
"group":"nogroup", "group":"nogroup",
"ttl":3600, "ttl":3600,
"timeout":1, "timeout":1,
"enable_cache":false,
"blacklist_ips":["ip.txt"], "blacklist_ips":["ip.txt"],
"rules":[ "rules":[
{ {

@ -46,6 +46,7 @@ func (r *routers) query(m *dns.Msg, servers []addr) (*dns.Msg, error) {
var up dnsClient var up dnsClient
var lastErr error var lastErr error
if r.c.EnableCache {
// query cache // query cache
m2 := r.cache.get(m) m2 := r.cache.get(m)
if m2 != nil { if m2 != nil {
@ -53,6 +54,7 @@ func (r *routers) query(m *dns.Msg, servers []addr) (*dns.Msg, error) {
m2.Id = m.Id m2.Id = m.Id
return m2, nil return m2, nil
} }
}
for _, srv := range servers { for _, srv := range servers {
switch srv.network { switch srv.network {
@ -70,7 +72,7 @@ func (r *routers) query(m *dns.Msg, servers []addr) (*dns.Msg, error) {
m1, _, err := up.Exchange(m, srv.addr) m1, _, err := up.Exchange(m, srv.addr)
if err == nil && !r.checkBlacklist(m) { if err == nil && !r.checkBlacklist(m) {
if m1.Rcode == dns.RcodeSuccess { if m1.Rcode == dns.RcodeSuccess && r.c.EnableCache {
// store to cache // store to cache
r.cache.set(m1) r.cache.set(m1)
} }
@ -118,11 +120,15 @@ func (r *routers) ServeDNS(w dns.ResponseWriter, m *dns.Msg) {
} }
func initRouters(c *cfg) { func initRouters(c *cfg) {
var cache1 *cache = nil
if c.EnableCache {
cache1 = newCache(1000, int64(c.TTL)) // cache 5 hours
}
router := &routers{ router := &routers{
c, c,
&dns.Client{Net: "tcp", Timeout: time.Duration(c.Timeout) * time.Second}, &dns.Client{Net: "tcp", Timeout: time.Duration(c.Timeout) * time.Second},
&dns.Client{Net: "udp", Timeout: time.Duration(c.Timeout) * time.Second}, &dns.Client{Net: "udp", Timeout: time.Duration(c.Timeout) * time.Second},
newCache(1000, int64(c.TTL)), // cache 5 hours cache1,
} }
dns.Handle(".", router) dns.Handle(".", router)
} }

Loading…
Cancel
Save