distcache.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package distcache
  2. import (
  3. "bytes"
  4. "encoding/gob"
  5. "errors"
  6. "github.com/grafana/grafana/pkg/log"
  7. "github.com/grafana/grafana/pkg/services/sqlstore"
  8. "github.com/grafana/grafana/pkg/registry"
  9. )
  10. var (
  11. ErrCacheItemNotFound = errors.New("cache item not found")
  12. )
  13. func init() {
  14. registry.RegisterService(&DistributedCache{})
  15. }
  16. // Init initializes the service
  17. func (ds *DistributedCache) Init() error {
  18. ds.log = log.New("distributed.cache")
  19. // memory
  20. // redis
  21. // memcache
  22. // database. using SQLSTORE
  23. ds.Client = &databaseCache{SQLStore: ds.SQLStore}
  24. return nil
  25. }
  26. // DistributedCache allows Grafana to cache data outside its own process
  27. type DistributedCache struct {
  28. log log.Logger
  29. Client cacheStorage
  30. SQLStore *sqlstore.SqlStore `inject:""`
  31. }
  32. type Item struct {
  33. Val interface{}
  34. Created int64
  35. Expire int64
  36. }
  37. func EncodeGob(item *Item) ([]byte, error) {
  38. buf := bytes.NewBuffer(nil)
  39. err := gob.NewEncoder(buf).Encode(item)
  40. return buf.Bytes(), err
  41. }
  42. func DecodeGob(data []byte, out *Item) error {
  43. buf := bytes.NewBuffer(data)
  44. return gob.NewDecoder(buf).Decode(&out)
  45. }
  46. type cacheStorage interface {
  47. // Get reads object from Cache
  48. Get(key string) (interface{}, error)
  49. // Puts an object into the cache
  50. Put(key string, value interface{}, expire int64) error
  51. // Delete object from cache
  52. Delete(key string) error
  53. }