param.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package param
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strconv"
  7. "time"
  8. "go-common/app/interface/main/app-resource/conf"
  9. "go-common/app/interface/main/app-resource/dao/param"
  10. "go-common/app/interface/main/app-resource/model"
  11. mparam "go-common/app/interface/main/app-resource/model/param"
  12. "go-common/library/ecode"
  13. "go-common/library/log"
  14. farm "github.com/dgryski/go-farm"
  15. )
  16. const (
  17. _initVersion = "param_version"
  18. _platKey = "param_%d"
  19. )
  20. // Service param service.
  21. type Service struct {
  22. dao *param.Dao
  23. tick time.Duration
  24. // model param cache
  25. cache map[string][]*mparam.Param
  26. }
  27. // New new a param service.
  28. func New(c *conf.Config) (s *Service) {
  29. s = &Service{
  30. dao: param.New(c),
  31. tick: time.Duration(c.Tick),
  32. cache: map[string][]*mparam.Param{},
  33. }
  34. s.load()
  35. go s.loadproc()
  36. return
  37. }
  38. // Param return param to string
  39. func (s *Service) Param(plat int8, build int, ver string) (res map[string]string, version string, err error) {
  40. res, version, err = s.getCache(plat, build, ver)
  41. return
  42. }
  43. func (s *Service) getCache(plat int8, build int, ver string) (res map[string]string, version string, err error) {
  44. var (
  45. pk = fmt.Sprintf(_platKey, plat)
  46. )
  47. res = map[string]string{}
  48. for _, p := range s.cache[pk] {
  49. if model.InvalidBuild(build, p.Build, p.Condition) {
  50. continue
  51. }
  52. res[p.Name] = p.Value
  53. }
  54. if version = s.hash(res); version == ver {
  55. err = ecode.NotModified
  56. res = nil
  57. }
  58. return
  59. }
  60. func (s *Service) load() {
  61. tmp, err := s.dao.All(context.TODO())
  62. if err != nil {
  63. log.Error("param s.dao.All() error(%v)", err)
  64. return
  65. }
  66. s.cache = tmp
  67. log.Info("param cacheproc success")
  68. }
  69. // cacheproc load cache data
  70. func (s *Service) loadproc() {
  71. for {
  72. time.Sleep(s.tick)
  73. s.load()
  74. }
  75. }
  76. func (s *Service) hash(v map[string]string) string {
  77. bs, err := json.Marshal(v)
  78. if err != nil {
  79. log.Error("json.Marshal error(%v)", err)
  80. return _initVersion
  81. }
  82. return strconv.FormatUint(farm.Hash64(bs), 10)
  83. }
  84. // key get banner cache key.
  85. func (s *Service) key(plat int8, build int) string {
  86. return fmt.Sprintf("%d_%d", plat, build)
  87. }
  88. // Close dao
  89. func (s *Service) Close() {
  90. s.dao.Close()
  91. }