cache.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package datasources
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/infra/localcache"
  7. m "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/registry"
  9. )
  10. type CacheService interface {
  11. GetDatasource(datasourceID int64, user *m.SignedInUser, skipCache bool) (*m.DataSource, error)
  12. }
  13. type CacheServiceImpl struct {
  14. Bus bus.Bus `inject:""`
  15. CacheService *localcache.CacheService `inject:""`
  16. }
  17. func init() {
  18. registry.Register(&registry.Descriptor{
  19. Name: "DatasourceCacheService",
  20. Instance: &CacheServiceImpl{},
  21. InitPriority: registry.Low,
  22. })
  23. }
  24. func (dc *CacheServiceImpl) Init() error {
  25. return nil
  26. }
  27. func (dc *CacheServiceImpl) GetDatasource(datasourceID int64, user *m.SignedInUser, skipCache bool) (*m.DataSource, error) {
  28. cacheKey := fmt.Sprintf("ds-%d", datasourceID)
  29. if !skipCache {
  30. if cached, found := dc.CacheService.Get(cacheKey); found {
  31. ds := cached.(*m.DataSource)
  32. if ds.OrgId == user.OrgId {
  33. return ds, nil
  34. }
  35. }
  36. }
  37. query := m.GetDataSourceByIdQuery{Id: datasourceID, OrgId: user.OrgId}
  38. if err := dc.Bus.Dispatch(&query); err != nil {
  39. return nil, err
  40. }
  41. dc.CacheService.Set(cacheKey, query.Result, time.Second*5)
  42. return query.Result, nil
  43. }