grafana/pkg/infra/remotecache/memcached_storage.go

65 lines
1.3 KiB
Go
Raw Normal View History

2019-03-08 13:49:16 -06:00
package remotecache
2019-02-23 11:28:33 -06:00
import (
"time"
"github.com/bradfitz/gomemcache/memcache"
2019-03-03 14:48:00 -06:00
"github.com/grafana/grafana/pkg/setting"
2019-02-23 11:28:33 -06:00
)
type memcachedStorage struct {
2019-02-23 11:28:33 -06:00
c *memcache.Client
}
2019-03-08 13:49:16 -06:00
func newMemcachedStorage(opts *setting.RemoteCacheOptions) *memcachedStorage {
return &memcachedStorage{
2019-03-03 14:48:00 -06:00
c: memcache.New(opts.ConnStr),
2019-02-23 11:28:33 -06:00
}
}
func newItem(sid string, data []byte, expire int32) *memcache.Item {
2019-02-23 11:28:33 -06:00
return &memcache.Item{
Key: sid,
Value: data,
Expiration: expire,
}
}
2019-03-05 08:15:05 -06:00
// Set sets value to given key in the cache.
func (s *memcachedStorage) Set(key string, val interface{}, expires time.Duration) error {
item := &cachedItem{Val: val}
bytes, err := encodeGob(item)
2019-02-23 11:28:33 -06:00
if err != nil {
return err
}
2019-03-05 08:34:51 -06:00
memcachedItem := newItem(key, bytes, int32(expires))
return s.c.Set(memcachedItem)
2019-02-23 11:28:33 -06:00
}
// Get gets value by given key in the cache.
func (s *memcachedStorage) Get(key string) (interface{}, error) {
2019-03-05 08:34:51 -06:00
memcachedItem, err := s.c.Get(key)
2019-03-02 21:42:11 -06:00
if err != nil && err.Error() == "memcache: cache miss" {
return nil, ErrCacheItemNotFound
}
2019-02-23 11:28:33 -06:00
if err != nil {
return nil, err
}
item := &cachedItem{}
2019-02-23 11:28:33 -06:00
2019-03-05 08:34:51 -06:00
err = decodeGob(memcachedItem.Value, item)
2019-02-23 11:28:33 -06:00
if err != nil {
return nil, err
}
return item.Val, nil
}
// Delete delete a key from the cache
func (s *memcachedStorage) Delete(key string) error {
2019-02-23 11:28:33 -06:00
return s.c.Delete(key)
}