-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
58 lines (48 loc) · 1.48 KB
/
set.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
package memcache
import (
"fmt"
"math/rand"
"strings"
"github.com/bradfitz/gomemcache/memcache"
"github.com/pkg/errors"
)
// SetWithTags sets a cache with key and tag(s). the cache can be invalidated by either of key or a tag.
func (c *Client) SetWithTags(item *memcache.Item, tags []string) error {
keystr, err := c.generateKeyStr(item.Key, tags)
if err != nil {
return errors.Wrap(err, "failed to generate revision key string")
}
item.Key = keystr
return c.Client.Set(item)
}
func (c *Client) generateKeyStr(k string, tags []string) (string, error) {
keys := append(tags, k)
revisions := make([]string, len(keys))
keyValueMap, err := c.GetMulti(keys)
if err != nil {
return "", errors.Wrap(err, fmt.Sprintf("failed to get tag values. %v", tags))
}
for j := 0; j < len(keys); j++ {
if revision, ok := keyValueMap[keys[j]]; ok {
revisions[j] = convertByteToString(revision.Value)
} else {
rev := createRevision()
revisions[j] = convertByteToString(rev)
err = c.setRevision(keys[j], rev)
if err != nil {
return "", errors.Wrap(err, fmt.Sprintf("failed to set set revision cache. key=%v", k))
}
}
}
return strings.Join(revisions, ":"), nil
}
func createRevision() []byte {
return []byte(string(rand.Intn(100000)))
}
func (c *Client) setRevision(key string, revision []byte) error {
err := c.Client.Set(&memcache.Item{Key: key, Value: revision})
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to set revision. key=%v", key))
}
return nil
}