Add redis
This commit is contained in:
57
redis.go
Normal file
57
redis.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/gomodule/redigo/redis"
|
||||
)
|
||||
|
||||
type Redis struct {
|
||||
client redis.Conn
|
||||
}
|
||||
|
||||
func NewRedis(addr, user, pass string) (*Redis, error) {
|
||||
opts := []redis.DialOption{}
|
||||
if pass != "" {
|
||||
opts = append(opts, redis.DialPassword(pass))
|
||||
}
|
||||
opts = append(opts, redis.DialConnectTimeout(time.Second*10))
|
||||
client, err := redis.Dial("tcp", addr, opts...)
|
||||
return &Redis{
|
||||
client: client,
|
||||
}, err
|
||||
}
|
||||
|
||||
func (m *Redis) String() string {
|
||||
return fmt.Sprintf("%v", *m)
|
||||
}
|
||||
|
||||
func (m *Redis) Close() error {
|
||||
return m.client.Close()
|
||||
}
|
||||
|
||||
func (m *Redis) Get(key string, ns ...string) ([]byte, error) {
|
||||
key = resolveNamespace(append(ns, key))
|
||||
log.Println(key)
|
||||
resp, err := m.client.Do("GET", key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
b, ok := resp.([]byte)
|
||||
if !ok {
|
||||
return nil, errors.New("resp not a []byte")
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (m *Redis) Set(key string, value []byte, ns ...string) error {
|
||||
namespace := resolveNamespace(append(ns, key))
|
||||
_, err := m.client.Do("SET", namespace, value)
|
||||
return err
|
||||
}
|
||||
Reference in New Issue
Block a user