cacheinterface/cache_redis.go

63 lines
979 B
Go

package cache
import (
"encoding/json"
"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) ([]byte, error) {
return rc.c.Get(key)
}
func (rc *RedisCache) Set(key string, val interface{}, ttl time.Duration) error {
var v []byte
if b, ok := val.([]byte); ok {
v = b
} else if s, ok := val.(string); ok {
b = []byte(s)
} else {
b, err := json.Marshal(val)
if err != nil {
return err
}
v = b
}
return rc.c.Setex(key, int64(ttl.Seconds()), v)
}
func (rc *RedisCache) Del(key string) error {
_, err := rc.c.Del(key)
return err
}