secondarycache.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package ccache
  2. import "time"
  3. type SecondaryCache struct {
  4. bucket *bucket
  5. pCache *LayeredCache
  6. }
  7. // Get the secondary key.
  8. // The semantics are the same as for LayeredCache.Get
  9. func (s *SecondaryCache) Get(secondary string) *Item {
  10. return s.bucket.get(secondary)
  11. }
  12. // Set the secondary key to a value.
  13. // The semantics are the same as for LayeredCache.Set
  14. func (s *SecondaryCache) Set(secondary string, value interface{}, duration time.Duration) *Item {
  15. item, existing := s.bucket.set(secondary, value, duration)
  16. if existing != nil {
  17. s.pCache.deletables <- existing
  18. }
  19. s.pCache.promote(item)
  20. return item
  21. }
  22. // Fetch or set a secondary key.
  23. // The semantics are the same as for LayeredCache.Fetch
  24. func (s *SecondaryCache) Fetch(secondary string, duration time.Duration, fetch func() (interface{}, error)) (*Item, error) {
  25. item := s.Get(secondary)
  26. if item != nil {
  27. return item, nil
  28. }
  29. value, err := fetch()
  30. if err != nil {
  31. return nil, err
  32. }
  33. return s.Set(secondary, value, duration), nil
  34. }
  35. // Delete a secondary key.
  36. // The semantics are the same as for LayeredCache.Delete
  37. func (s *SecondaryCache) Delete(secondary string) bool {
  38. item := s.bucket.delete(secondary)
  39. if item != nil {
  40. s.pCache.deletables <- item
  41. return true
  42. }
  43. return false
  44. }
  45. // Replace a secondary key.
  46. // The semantics are the same as for LayeredCache.Replace
  47. func (s *SecondaryCache) Replace(secondary string, value interface{}) bool {
  48. item := s.Get(secondary)
  49. if item == nil {
  50. return false
  51. }
  52. s.Set(secondary, value, item.TTL())
  53. return true
  54. }
  55. // Track a secondary key.
  56. // The semantics are the same as for LayeredCache.TrackingGet
  57. func (c *SecondaryCache) TrackingGet(secondary string) TrackedItem {
  58. item := c.Get(secondary)
  59. if item == nil {
  60. return NilTracked
  61. }
  62. item.track()
  63. return item
  64. }