2019-10-02 04:10:27 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2019-10-03 00:17:34 +00:00
|
|
|
func (rc *RedisCache) Get(key string, dst ...interface{}) ([]byte, error) {
|
|
|
|
b, err := rc.c.Get(key)
|
2019-10-02 04:10:27 +00:00
|
|
|
|
2019-10-03 00:17:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-10-02 04:10:27 +00:00
|
|
|
|
2019-10-03 00:17:34 +00:00
|
|
|
if len(dst) > 0 && dst[0] != nil {
|
|
|
|
return decodeDst(b, dst[0])
|
|
|
|
}
|
2019-10-02 04:10:27 +00:00
|
|
|
|
2019-10-03 00:17:34 +00:00
|
|
|
return b, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rc *RedisCache) Set(key string, val interface{}, ttl time.Duration) error {
|
|
|
|
v, err := encodeValue(val)
|
2019-10-02 04:10:27 +00:00
|
|
|
|
2019-10-03 00:17:34 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2019-10-02 04:10:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return rc.c.Setex(key, int64(ttl.Seconds()), v)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rc *RedisCache) Del(key string) error {
|
|
|
|
_, err := rc.c.Del(key)
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|