glider/dns/cache.go

90 lines
1.7 KiB
Go
Raw Normal View History

package dns
import (
"sync"
"time"
2020-08-23 23:23:30 +08:00
"github.com/nadoo/glider/common/pool"
)
// LongTTL is 50 years duration in seconds, used for none-expired items.
const LongTTL = 50 * 365 * 24 * 3600
type item struct {
value []byte
expire time.Time
}
// Cache is the struct of cache.
type Cache struct {
2020-08-23 23:23:30 +08:00
store map[string]*item
mutex sync.RWMutex
storeCopy bool
}
// NewCache returns a new cache.
2020-08-23 23:23:30 +08:00
func NewCache(storeCopy bool) (c *Cache) {
c = &Cache{store: make(map[string]*item), storeCopy: storeCopy}
go func() {
for now := range time.Tick(time.Second) {
2020-08-23 23:23:30 +08:00
c.mutex.Lock()
for k, v := range c.store {
if now.After(v.expire) {
2020-08-23 23:23:30 +08:00
delete(c.store, k)
if storeCopy {
pool.PutBuffer(v.value)
}
}
}
2020-08-23 23:23:30 +08:00
c.mutex.Unlock()
}
}()
return
}
// Len returns the length of cache.
func (c *Cache) Len() int {
2020-08-23 23:23:30 +08:00
return len(c.store)
}
// Put an item into cache, invalid after ttl seconds.
func (c *Cache) Put(k string, v []byte, ttl int) {
if len(v) != 0 {
2020-08-23 23:23:30 +08:00
c.mutex.Lock()
it, ok := c.store[k]
if !ok {
2020-08-23 23:23:30 +08:00
if c.storeCopy {
it = &item{value: valCopy(v)}
} else {
it = &item{value: v}
}
c.store[k] = it
}
it.expire = time.Now().Add(time.Duration(ttl) * time.Second)
2020-08-23 23:23:30 +08:00
c.mutex.Unlock()
}
}
2020-08-23 23:23:30 +08:00
// Get gets an item from cache(do not modify it).
func (c *Cache) Get(k string) (v []byte) {
2020-08-23 23:23:30 +08:00
c.mutex.RLock()
if it, ok := c.store[k]; ok {
v = it.value
}
2020-08-23 23:23:30 +08:00
c.mutex.RUnlock()
return
}
// GetCopy gets an item from cache and returns it's copy(so you can modify it).
func (c *Cache) GetCopy(k string) []byte {
return valCopy(c.Get(k))
}
func valCopy(v []byte) (b []byte) {
if v != nil {
b = pool.GetBuffer(len(v))
copy(b, v)
}
return
}