forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memcached.go
66 lines (53 loc) · 1.12 KB
/
memcached.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
package memcached
import (
"time"
mc "github.com/bradfitz/gomemcache/memcache"
"github.com/micro/go-os/kv"
)
type mkv struct {
Client *mc.Client
}
func (m *mkv) Close() error {
return nil
}
func (m *mkv) Get(key string) (*kv.Item, error) {
keyval, err := m.Client.Get(key)
if err != nil && err == mc.ErrCacheMiss {
return nil, kv.ErrNotFound
} else if err != nil {
return nil, err
}
if keyval == nil {
return nil, kv.ErrNotFound
}
return &kv.Item{
Key: keyval.Key,
Value: keyval.Value,
Expiration: time.Second * time.Duration(keyval.Expiration),
}, nil
}
func (m *mkv) Del(key string) error {
return m.Client.Delete(key)
}
func (m *mkv) Put(item *kv.Item) error {
return m.Client.Set(&mc.Item{
Key: item.Key,
Value: item.Value,
Expiration: int32(item.Expiration.Seconds()),
})
}
func (m *mkv) String() string {
return "memcached"
}
func NewKV(opts ...kv.Option) kv.KV {
var options kv.Options
for _, o := range opts {
o(&options)
}
if len(options.Servers) == 0 {
options.Servers = []string{"127.0.0.1:11211"}
}
return &mkv{
Client: mc.New(options.Servers...),
}
}