syscfg_cache.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package main
  2. import (
  3. "redisdog/model"
  4. )
  5. type SysCfgCache struct {
  6. lock chan int
  7. data map[string]string
  8. }
  9. func NewSysCfgCache() *SysCfgCache {
  10. return &SysCfgCache{
  11. lock: make(chan int, 1),
  12. data: make(map[string]string),
  13. }
  14. }
  15. func (s *SysCfgCache) Load() error {
  16. mdl := model.NewSysCfg(Db)
  17. values, err := mdl.GetAll()
  18. if err != nil {
  19. return err
  20. }
  21. s.lock <- 1
  22. for _, item := range values {
  23. s.data[item.CfgKey] = item.CfgValue
  24. }
  25. <-s.lock
  26. return nil
  27. }
  28. func (s *SysCfgCache) Get(k string) (string, bool) {
  29. s.lock <- 1
  30. v, ok := s.data[k]
  31. <-s.lock
  32. return v, ok
  33. }
  34. func (s *SysCfgCache) Set(k, v string) {
  35. s.lock <- 1
  36. s.data[k] = v
  37. <-s.lock
  38. }
  39. func (s *SysCfgCache) GetMulti(keys []string) map[string]string {
  40. s.lock <- 1
  41. cpy := make(map[string]string)
  42. for _, key := range keys {
  43. v, ok := s.data[key]
  44. if ok {
  45. cpy[key] = v
  46. } else {
  47. cpy[key] = ""
  48. }
  49. }
  50. <-s.lock
  51. return cpy
  52. }
  53. func (s *SysCfgCache) GetAll() map[string]string {
  54. s.lock <- 1
  55. cpy := make(map[string]string)
  56. for k, v := range s.data {
  57. cpy[k] = v
  58. }
  59. <-s.lock
  60. return cpy
  61. }