Initial v2 version, better testing, updates
Some checks failed
continuous-integration/drone Build is failing
Some checks failed
continuous-integration/drone Build is failing
This commit is contained in:
73
driver/redis/redis.go
Normal file
73
driver/redis/redis.go
Normal file
@ -0,0 +1,73 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"github.com/hoisie/redis"
|
||||
"meow.tf/go/cacheinterface/v2/encoder"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Encoder encoder.Encoder `query:"encoder" default:"msgpack"`
|
||||
Address string `default:"127.0.0.1"`
|
||||
DB int `default:"0" query:"db"`
|
||||
Password string `query:"password"`
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
options Options
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func New(options Options) (*Cache, error) {
|
||||
rc := &redis.Client{
|
||||
Addr: options.Address,
|
||||
Db: options.DB,
|
||||
Password: options.Password,
|
||||
}
|
||||
|
||||
return &Cache{
|
||||
options: options,
|
||||
client: rc,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (rc *Cache) Has(key string) bool {
|
||||
b, _ := rc.client.Exists(key)
|
||||
return b
|
||||
}
|
||||
|
||||
func (rc *Cache) Get(key string, dst any) error {
|
||||
b, err := rc.client.Get(key)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return encoder.DecodeValue(rc.options.Encoder, b, dst)
|
||||
}
|
||||
|
||||
func (rc *Cache) GetBytes(key string) ([]byte, error) {
|
||||
b, err := rc.client.Get(key)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (rc *Cache) Set(key string, val any, ttl time.Duration) error {
|
||||
v, err := encoder.EncodeValue(rc.options.Encoder, val)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return rc.client.Setex(key, int64(ttl.Seconds()), v)
|
||||
}
|
||||
|
||||
func (rc *Cache) Del(key string) error {
|
||||
_, err := rc.client.Del(key)
|
||||
|
||||
return err
|
||||
}
|
Reference in New Issue
Block a user