Skip to content

Commit

Permalink
feat(cache): shuffle record
Browse files Browse the repository at this point in the history
  • Loading branch information
wolf-joe committed Mar 26, 2020
1 parent 14d9345 commit ce8ee8a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
8 changes: 7 additions & 1 deletion cache/dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cache
import (
"fmt"
"github.com/miekg/dns"
"math/rand"
"strconv"
"time"
)
Expand Down Expand Up @@ -58,7 +59,12 @@ func (cache *DNSCache) Get(request *dns.Msg) *dns.Msg {
cacheKey += "." + subnet
}
if cacheHit, ok := cache.ttlMap.Get(cacheKey); ok {
return cacheHit.(*cacheEntry).Get()
r := cacheHit.(*cacheEntry).Get()
rand.Seed(time.Now().UnixNano()) // random record order
rand.Shuffle(len(r.Answer), func(i, j int) {
r.Answer[i], r.Answer[j] = r.Answer[j], r.Answer[i]
})
return r
}
return nil
}
Expand Down
7 changes: 5 additions & 2 deletions cache/dns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,13 @@ func TestGetDNSCache(t *testing.T) {
}

func TestTTLRewrite(t *testing.T) {
rr, _ := dns.NewRR("ip.cn. 0 IN A 1.1.1.1")
req, resp := &dns.Msg{}, &dns.Msg{Answer: []dns.RR{rr}}
rr1, _ := dns.NewRR("ip.cn. 0 IN A 1.1.1.1")
rr2, _ := dns.NewRR("ip.cn. 0 IN A 1.1.1.2")
req, resp := &dns.Msg{}, &dns.Msg{Answer: []dns.RR{rr1, rr2}}
req.SetQuestion("ip.cn.", dns.TypeA)
cache := NewDNSCache(1, time.Minute, time.Hour*24)
cache.Set(req, resp)
assert.NotEqual(t, resp.Answer[0].Header().Ttl, uint32(0))
// 顺便测试random record order
cache.Get(req)
}

0 comments on commit ce8ee8a

Please sign in to comment.