distcache.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package distcache
  2. import (
  3. "bytes"
  4. "encoding/gob"
  5. "errors"
  6. "time"
  7. "github.com/grafana/grafana/pkg/log"
  8. "github.com/grafana/grafana/pkg/services/sqlstore"
  9. redis "gopkg.in/redis.v2"
  10. "github.com/grafana/grafana/pkg/registry"
  11. )
  12. var (
  13. ErrCacheItemNotFound = errors.New("cache item not found")
  14. )
  15. func init() {
  16. registry.RegisterService(&DistributedCache{})
  17. }
  18. // Init initializes the service
  19. func (ds *DistributedCache) Init() error {
  20. ds.log = log.New("distributed.cache")
  21. ds.Client = createClient(CacheOpts{}, ds.SQLStore)
  22. return nil
  23. }
  24. type CacheOpts struct {
  25. name string
  26. }
  27. func createClient(opts CacheOpts, sqlstore *sqlstore.SqlStore) cacheStorage {
  28. if opts.name == "redis" {
  29. opt := &redis.Options{
  30. Network: "tcp",
  31. Addr: "localhost:6379",
  32. }
  33. return newRedisStorage(redis.NewClient(opt))
  34. }
  35. if opts.name == "memcache" {
  36. return newMemcacheStorage("localhost:11211")
  37. }
  38. if opts.name == "memory" {
  39. return newMemoryStorage()
  40. }
  41. return newDatabaseCache(sqlstore)
  42. }
  43. // DistributedCache allows Grafana to cache data outside its own process
  44. type DistributedCache struct {
  45. log log.Logger
  46. Client cacheStorage
  47. SQLStore *sqlstore.SqlStore `inject:""`
  48. }
  49. type cachedItem struct {
  50. Val interface{}
  51. }
  52. func encodeGob(item *cachedItem) ([]byte, error) {
  53. buf := bytes.NewBuffer(nil)
  54. err := gob.NewEncoder(buf).Encode(item)
  55. return buf.Bytes(), err
  56. }
  57. func decodeGob(data []byte, out *cachedItem) error {
  58. buf := bytes.NewBuffer(data)
  59. return gob.NewDecoder(buf).Decode(&out)
  60. }
  61. type cacheStorage interface {
  62. // Get reads object from Cache
  63. Get(key string) (interface{}, error)
  64. // Puts an object into the cache
  65. Put(key string, value interface{}, expire time.Duration) error
  66. // Delete object from cache
  67. Delete(key string) error
  68. }