item.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package cache
  15. import (
  16. "time"
  17. expirationcache "yunion.io/x/pkg/util/cache"
  18. )
  19. type UpdateFunc func([]string) ([]interface{}, error)
  20. type LoadFunc func() ([]interface{}, error)
  21. type GetUpdateFunc func(d []interface{}) ([]string, error)
  22. // Item implement CachedItem interface
  23. type Item struct {
  24. // Name of this cache item
  25. name string
  26. // Time to live duration
  27. ttl time.Duration
  28. // Load all objects period
  29. period time.Duration
  30. // Function to get index like id or name of this cache item
  31. keyFunc expirationcache.KeyFunc
  32. // Function to update range of cache item by their key
  33. update UpdateFunc
  34. // Function to load all cache items
  35. load LoadFunc
  36. // Function to get item must be updated
  37. getUpdate GetUpdateFunc
  38. }
  39. // NewCacheItem new a Item implement CachedItem interface
  40. func NewCacheItem(name string, ttl, period time.Duration,
  41. keyf expirationcache.KeyFunc,
  42. update UpdateFunc, load LoadFunc,
  43. getUpdate GetUpdateFunc,
  44. ) CachedItem {
  45. return &Item{
  46. name: name,
  47. ttl: ttl,
  48. period: period,
  49. keyFunc: keyf,
  50. update: update,
  51. load: load,
  52. getUpdate: getUpdate,
  53. }
  54. }
  55. func (h *Item) TTL() time.Duration {
  56. return h.ttl
  57. }
  58. func (h *Item) Key(obj interface{}) (string, error) {
  59. return h.keyFunc(obj)
  60. }
  61. func (h *Item) Name() string {
  62. return h.name
  63. }
  64. func (h *Item) Period() time.Duration {
  65. return h.period
  66. }
  67. func (h *Item) Update(ids []string) ([]interface{}, error) {
  68. return h.update(ids)
  69. }
  70. func (h *Item) Load() ([]interface{}, error) {
  71. return h.load()
  72. }
  73. func (h *Item) GetUpdate(d []interface{}) ([]string, error) {
  74. return h.getUpdate(d)
  75. }