cacheinterface/redis.go

62 lines
973 B
Go

package cache
import (
"github.com/hoisie/redis"
"time"
)
type RedisSettings struct {
Address string
DB int
Password string
}
type RedisCache struct {
CacheInterface
c *redis.Client
}
func NewRedisCache(c RedisSettings) (CacheInterface, error) {
rc := &redis.Client{Addr: c.Address, Db: c.DB, Password: c.Password}
return &RedisCache{
c: rc,
}, nil
}
func (rc *RedisCache) Has(key string) bool {
b, _ := rc.c.Exists(key)
return b
}
func (rc *RedisCache) Get(key string, dst ...interface{}) ([]byte, error) {
b, err := rc.c.Get(key)
if err != nil {
return nil, err
}
if len(dst) > 0 && dst[0] != nil {
return decodeDst(b, dst[0])
}
return b, err
}
func (rc *RedisCache) Set(key string, val interface{}, ttl time.Duration) error {
v, err := encodeValue(val)
if err != nil {
return err
}
return rc.c.Setex(key, int64(ttl.Seconds()), v)
}
func (rc *RedisCache) Del(key string) error {
_, err := rc.c.Del(key)
return err
}