/
memcacheclient.go
93 lines (74 loc) · 2.1 KB
/
memcacheclient.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package gomemcacheclient
/**
* @author jotaoverride
*/
import (
"bytes"
"encoding/gob"
"errors"
"github.com/bradfitz/gomemcache/memcache"
"time"
)
type MemcacheClient struct {
client *memcache.Client
defaultExpiration int32
}
// Create a new Client.
// Config must have the servers array.
// Optional the defaultExpiration.
func (c *MemcacheClient) ConnectClient(servers []string, defaultExpiration ...int32) (err error) {
selector := new(memcache.ServerList)
err = selector.SetServers(servers...)
if err == nil {
c.client = memcache.NewFromSelector(selector)
c.client.Timeout = 200 * time.Millisecond // Default timeout: 200 ms.
if defaultExpiration != nil {
c.defaultExpiration = defaultExpiration[0]
} else {
c.defaultExpiration = 60 * 15 // Default expiration time: 15 minutes.
}
// Test the connection...
if _, testErr := c.client.Get("GOLANG_TEST"); testErr != nil && testErr.Error() != "memcache: cache miss" {
err = errors.New("Can't connect to the servers")
}
}
return
}
func (c *MemcacheClient) SetDefaultExpiration(secs int32) {
c.defaultExpiration = secs
}
func (c *MemcacheClient) Get(key string, value interface{}) (err error) {
item, err := c.client.Get(key)
if err == nil {
err = decode(item.Value, value)
}
return err
}
func (c *MemcacheClient) Set(key string, value interface{}, expiration ...int32) (err error) {
valueEncoded, err := encode(value)
if err == nil {
if expiration != nil {
err = c.client.Set(&memcache.Item{Key: key, Value: valueEncoded, Expiration: expiration[0]})
} else {
err = c.client.Set(&memcache.Item{Key: key, Value: valueEncoded, Expiration: c.defaultExpiration})
}
}
return
}
func (c *MemcacheClient) Delete(key string) error {
return c.client.Delete(key)
}
// Auxiliary functions
func encode(value interface{}) (encodedValue []byte, err error) {
buf := new(bytes.Buffer)
enc := gob.NewEncoder(buf)
err = enc.Encode(value)
if err == nil {
encodedValue = buf.Bytes()
}
return
}
func decode(value []byte, result interface{}) error {
dec := gob.NewDecoder(bytes.NewBuffer(value))
return dec.Decode(result)
}