forked from faabiosr/cachego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memcached.go
71 lines (57 loc) · 1.59 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
67
68
69
70
71
// Package memcached providers a cache driver that stores the cache in Memcached.
package memcached
import (
"time"
"github.com/bradfitz/gomemcache/memcache"
"github.com/faabiosr/cachego"
)
type memcached struct {
driver *memcache.Client
}
// New creates an instance of Memcached cache driver
func New(driver *memcache.Client) cachego.Cache {
return &memcached{driver}
}
// Contains checks if cached key exists in Memcached storage
func (m *memcached) Contains(key string) bool {
_, err := m.Fetch(key)
return err == nil
}
// Delete the cached key from Memcached storage
func (m *memcached) Delete(key string) error {
return m.driver.Delete(key)
}
// Fetch retrieves the cached value from key of the Memcached storage
func (m *memcached) Fetch(key string) (string, error) {
item, err := m.driver.Get(key)
if err != nil {
return "", err
}
return string(item.Value), nil
}
// FetchMulti retrieves multiple cached value from keys of the Memcached storage
func (m *memcached) FetchMulti(keys []string) map[string]string {
result := make(map[string]string)
items, err := m.driver.GetMulti(keys)
if err != nil {
return result
}
for _, i := range items {
result[i.Key] = string(i.Value)
}
return result
}
// Flush removes all cached keys of the Memcached storage
func (m *memcached) Flush() error {
return m.driver.FlushAll()
}
// Save a value in Memcached storage by key
func (m *memcached) Save(key string, value string, lifeTime time.Duration) error {
return m.driver.Set(
&memcache.Item{
Key: key,
Value: []byte(value),
Expiration: int32(lifeTime.Seconds()),
},
)
}