cache.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Package cache provides partial implementations of Guava Cache,
  2. // including support for LRU, Segmented LRU and TinyLFU.
  3. package cache
  4. // Key is any value which is comparable.
  5. // See http://golang.org/ref/spec#Comparison_operators for details.
  6. type Key interface{}
  7. // Value is any value.
  8. type Value interface{}
  9. // Cache is a key-value cache which entries are added and stayed in the
  10. // cache until either are evicted or manually invalidated.
  11. type Cache interface {
  12. // GetIfPresent returns value associated with Key or (nil, false)
  13. // if there is no cached value for Key.
  14. GetIfPresent(Key) (Value, bool)
  15. // Put associates value with Key. If a value is already associated
  16. // with Key, the old one will be replaced with Value.
  17. Put(Key, Value)
  18. // Invalidate discards cached value of the given Key.
  19. Invalidate(Key)
  20. // InvalidateAll discards all entries.
  21. InvalidateAll()
  22. // Stats copies cache statistics to given Stats pointer.
  23. Stats(*Stats)
  24. // Close implements io.Closer for cleaning up all resources.
  25. // Users must ensure the cache is not being used before closing or
  26. // after closed.
  27. Close() error
  28. }
  29. // Func is a generic callback for entry events in the cache.
  30. type Func func(Key, Value)
  31. // LoadingCache is a cache with values are loaded automatically and stored
  32. // in the cache until either evicted or manually invalidated.
  33. type LoadingCache interface {
  34. Cache
  35. // Get returns value associated with Key or call underlying LoaderFunc
  36. // to load value if it is not present.
  37. Get(Key) (Value, error)
  38. // Refresh loads new value for Key. If the Key already existed, the previous value
  39. // will continue to be returned by Get while the new value is loading.
  40. // If Key does not exist, this function will block until the value is loaded.
  41. Refresh(Key)
  42. }
  43. // LoaderFunc retrieves the value corresponding to given Key.
  44. type LoaderFunc func(Key) (Value, error)
  45. // Executor specifies how cache loader is run to refresh value for the Key.
  46. // By default, it is run in a new go routine.
  47. type Executor interface {
  48. // Execute runs the fn asynchronously.
  49. Execute(fn func())
  50. // Close shuts down all running tasks. Currently, the error returned is not being used.
  51. Close() error
  52. }