cache.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 db
  15. import (
  16. "database/sql"
  17. "sync"
  18. "yunion.io/x/pkg/errors"
  19. )
  20. type ICacheable interface {
  21. GetId() string
  22. }
  23. type SCacheManager[T ICacheable] struct {
  24. cache *sync.Map
  25. manager IStandaloneModelManager
  26. }
  27. func NewCacheManager[T ICacheable](manager IStandaloneModelManager) *SCacheManager[T] {
  28. return &SCacheManager[T]{
  29. cache: &sync.Map{},
  30. manager: manager,
  31. }
  32. }
  33. func (cm *SCacheManager[T]) Invalidate() {
  34. cm.cache = nil
  35. }
  36. func (cm *SCacheManager[T]) FetchById(id string) (*T, error) {
  37. if cm.cache == nil {
  38. cm.fetchCacheFromDB()
  39. }
  40. m, ok := cm.cache.Load(id)
  41. if ok {
  42. return m.(*T), nil
  43. } else {
  44. return nil, errors.Wrapf(sql.ErrNoRows, "no such id %s", id)
  45. }
  46. }
  47. func (cm *SCacheManager[T]) fetchCacheFromDB() error {
  48. q := cm.manager.Query()
  49. ret := make([]T, 0)
  50. err := FetchModelObjects(cm.manager, q, &ret)
  51. if err != nil {
  52. return errors.Wrap(err, "FetchModelObjects")
  53. }
  54. cache := &sync.Map{}
  55. for i := range ret {
  56. cache.Store(ret[i].GetId(), &ret[i])
  57. }
  58. cm.cache = cache
  59. return nil
  60. }
  61. func (cm *SCacheManager[T]) Update(obj *T) {
  62. cm.cache.Store((*obj).GetId(), obj)
  63. }
  64. func (cm *SCacheManager[T]) Delete(obj *T) {
  65. cm.cache.Delete((*obj).GetId())
  66. }
  67. func (cm *SCacheManager[T]) Range(proc func(key interface{}, value interface{}) bool) {
  68. if cm.cache == nil {
  69. cm.fetchCacheFromDB()
  70. }
  71. cm.cache.Range(proc)
  72. }