service.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package operation
  2. import (
  3. "context"
  4. "strconv"
  5. "time"
  6. "go-common/app/interface/main/web-show/conf"
  7. "go-common/app/interface/main/web-show/dao/operation"
  8. opdml "go-common/app/interface/main/web-show/model/operation"
  9. arcrpc "go-common/app/service/main/archive/api/gorpc"
  10. "go-common/library/log"
  11. )
  12. const (
  13. _rankCacheLen = 20
  14. )
  15. // Service struct
  16. type Service struct {
  17. dao *operation.Dao
  18. arcRPC *arcrpc.Service2
  19. cache map[string]map[int][]*opdml.Operation
  20. }
  21. // New init
  22. func New(c *conf.Config) (s *Service) {
  23. s = &Service{
  24. cache: make(map[string]map[int][]*opdml.Operation, len(opdml.Types)),
  25. }
  26. s.arcRPC = arcrpc.New2(c.RPCClient2.Archive)
  27. s.dao = operation.New(c)
  28. s.reload()
  29. go s.loadproc()
  30. return
  31. }
  32. // Notice return notice info
  33. func (s *Service) operation(tp string, rank, num int) (res map[string][]*opdml.Operation) {
  34. res = make(map[string][]*opdml.Operation)
  35. tmp, ok := s.cache[tp]
  36. if ok {
  37. if rank != 0 {
  38. if ns := tmp[rank]; ns != nil {
  39. if len(ns) < num || num < 0 {
  40. num = len(ns)
  41. }
  42. ns = ns[:num]
  43. res[strconv.FormatInt(int64(rank), 10)] = ns
  44. }
  45. } else {
  46. for rk, ns := range tmp {
  47. if ns != nil {
  48. if len(ns) < num || num < 0 {
  49. num = len(ns)
  50. }
  51. ns = ns[:num]
  52. res[strconv.FormatInt(int64(rk), 10)] = ns
  53. }
  54. }
  55. }
  56. }
  57. return
  58. }
  59. // reload Service
  60. func (s *Service) reload() {
  61. var (
  62. tmpT = make(map[string]map[int][]*opdml.Operation)
  63. )
  64. ops, err := s.dao.Operation(context.Background())
  65. if err != nil {
  66. log.Error("s.reloadNotice error(%v)", err)
  67. return
  68. }
  69. for _, op := range ops {
  70. tmp, ok := tmpT[op.Type]
  71. if !ok {
  72. tmp = make(map[int][]*opdml.Operation)
  73. }
  74. if len(tmp) > _rankCacheLen {
  75. continue
  76. }
  77. tmp[op.Rank] = append(tmp[op.Rank], op)
  78. tmpT[op.Type] = tmp
  79. }
  80. s.cache = tmpT
  81. }
  82. // loadproc Service
  83. func (s *Service) loadproc() {
  84. for {
  85. s.reload()
  86. time.Sleep(time.Duration(conf.Conf.Reload.Notice))
  87. }
  88. }
  89. // Close Service
  90. func (s *Service) Close() {
  91. s.dao.Close()
  92. }
  93. // Ping Service
  94. func (s *Service) Ping(c context.Context) (err error) {
  95. err = s.dao.Ping(c)
  96. return
  97. }