71 lines
1.2 KiB
Go
71 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"github.com/hoisie/redis"
|
|
"github.com/miekg/dns"
|
|
)
|
|
|
|
func NewRedisCache(c RedisSettings, expire int32) *RedisCache {
|
|
rc := &redis.Client{Addr: c.Addr(), Db: c.DB, Password: c.Password}
|
|
|
|
return &RedisCache{
|
|
backend: rc,
|
|
expire: expire,
|
|
}
|
|
}
|
|
|
|
type RedisCache struct {
|
|
Cache
|
|
|
|
backend *redis.Client
|
|
expire int32
|
|
}
|
|
|
|
func (m *RedisCache) Set(key string, msg *dns.Msg) error {
|
|
var val []byte
|
|
var err error
|
|
|
|
// handle cases for negacache where it sets nil values
|
|
if msg == nil {
|
|
val = []byte("nil")
|
|
} else {
|
|
val, err = msg.Pack()
|
|
}
|
|
if err != nil {
|
|
err = SerializerError{err}
|
|
}
|
|
return m.backend.Setex(key, int64(m.expire), val)
|
|
}
|
|
|
|
func (m *RedisCache) Get(key string) (*dns.Msg, error) {
|
|
var msg dns.Msg
|
|
item, err := m.backend.Get(key)
|
|
if err != nil {
|
|
err = KeyNotFound{key}
|
|
return &msg, err
|
|
}
|
|
err = msg.Unpack(item)
|
|
if err != nil {
|
|
err = SerializerError{err}
|
|
}
|
|
return &msg, err
|
|
}
|
|
|
|
func (m *RedisCache) Exists(key string) bool {
|
|
exists, err := m.backend.Exists(key)
|
|
if err != nil {
|
|
return true
|
|
}
|
|
return exists
|
|
}
|
|
|
|
func (m *RedisCache) Remove(key string) error {
|
|
_, err := m.backend.Del(key)
|
|
return err
|
|
}
|
|
|
|
func (m *RedisCache) Full() bool {
|
|
// memcache is never full (LRU)
|
|
return false
|
|
}
|