/
kv_store.go
73 lines (58 loc) · 1.32 KB
/
kv_store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package common
import (
"context"
"errors"
"fmt"
"github.com/go-redis/redis"
"time"
)
type IKVStore interface {
Set(key string, value string, expire time.Duration) error
Get(key string) (string, error)
}
var KVStoreEmpty = errors.New("KVStoreEmpty")
func InitKVStore(config interface{}) (store IKVStore, err error) {
switch c := config.(type) {
case nil:
return nil, fmt.Errorf("need Config to init KVStore")
case *RedisKVStoreConfig:
KVStore := &RedisKVStore{}
err = KVStore.Init(c)
if err != nil {
return
}
return KVStore, nil
default:
return nil, fmt.Errorf("KVStore config is not support %v", config)
}
}
type (
RedisKVStore struct {
ctx context.Context
client *redis.Client
}
RedisKVStoreConfig struct {
Ctx context.Context
Client *redis.Client
}
)
func (queue RedisKVStore) Set(key, value string, expire time.Duration) error {
ret := queue.client.Set(key, value, expire)
return ret.Err()
}
func (queue RedisKVStore) Get(key string) (string, error) {
ret := queue.client.Get(key)
res, err := ret.Result()
if err == redis.Nil {
return "", KVStoreEmpty
}
return res, err
}
func (queue *RedisKVStore) Init(config *RedisKVStoreConfig) error {
if config.Client == nil {
return fmt.Errorf("no redis Connection")
}
queue.client = config.Client
queue.ctx = config.Ctx
return nil
}