forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmemcached_storage.go
63 lines (49 loc) · 1.4 KB
/
memcached_storage.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
package remotecache
import (
"context"
"errors"
"time"
"github.com/bradfitz/gomemcache/memcache"
"github.com/grafana/grafana/pkg/setting"
)
const memcachedCacheType = "memcached"
var ErrNotImplemented = errors.New("not implemented")
type memcachedStorage struct {
c *memcache.Client
}
func newMemcachedStorage(opts *setting.RemoteCacheOptions) *memcachedStorage {
return &memcachedStorage{
c: memcache.New(opts.ConnStr),
}
}
func newItem(sid string, data []byte, expire int32) *memcache.Item {
return &memcache.Item{
Key: sid,
Value: data,
Expiration: expire,
}
}
// SetByteArray stores an byte array in the cache
func (s *memcachedStorage) Set(ctx context.Context, key string, data []byte, expires time.Duration) error {
var expiresInSeconds int64
if expires != 0 {
expiresInSeconds = int64(expires) / int64(time.Second)
}
memcachedItem := newItem(key, data, int32(expiresInSeconds))
return s.c.Set(memcachedItem)
}
// GetByteArray returns the cached value as an byte array
func (s *memcachedStorage) Get(ctx context.Context, key string) ([]byte, error) {
memcachedItem, err := s.c.Get(key)
if errors.Is(err, memcache.ErrCacheMiss) {
return nil, ErrCacheItemNotFound
}
if err != nil {
return nil, err
}
return memcachedItem.Value, nil
}
// Delete delete a key from the cache
func (s *memcachedStorage) Delete(ctx context.Context, key string) error {
return s.c.Delete(key)
}