dao.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/service/main/history/conf"
  6. "go-common/app/service/main/history/model"
  7. "go-common/library/cache/redis"
  8. "go-common/library/database/tidb"
  9. "go-common/library/queue/databus"
  10. )
  11. // Dao dao
  12. type Dao struct {
  13. c *conf.Config
  14. tidb *tidb.DB
  15. redis *redis.Pool
  16. redisExpire int32
  17. mergeDbus *databus.Databus
  18. businessesStmt *tidb.Stmts
  19. historiesStmt *tidb.Stmts
  20. historyStmt *tidb.Stmts
  21. insertStmt *tidb.Stmts
  22. deleteHistoriesStmt *tidb.Stmts
  23. clearAllHistoriesStmt *tidb.Stmts
  24. userHideStmt *tidb.Stmts
  25. updateUserHideStmt *tidb.Stmts
  26. Businesses map[int64]*model.Business
  27. BusinessNames map[string]*model.Business
  28. }
  29. // New init mysql db
  30. func New(c *conf.Config) (dao *Dao) {
  31. dao = &Dao{
  32. c: c,
  33. redis: redis.NewPool(c.Redis.Config),
  34. tidb: tidb.NewTiDB(c.TiDB),
  35. mergeDbus: databus.New(c.DataBus.Merge),
  36. redisExpire: int32(time.Duration(c.Redis.Expire) / time.Second),
  37. }
  38. dao.businessesStmt = dao.tidb.Prepared(_businessesSQL)
  39. dao.historiesStmt = dao.tidb.Prepared(_historiesSQL)
  40. dao.deleteHistoriesStmt = dao.tidb.Prepared(_deleteHistoriesSQL)
  41. dao.clearAllHistoriesStmt = dao.tidb.Prepared(_clearAllHistoriesSQL)
  42. dao.historyStmt = dao.tidb.Prepared(_historySQL)
  43. dao.userHideStmt = dao.tidb.Prepared(_userHide)
  44. dao.updateUserHideStmt = dao.tidb.Prepared(_updateUserHide)
  45. dao.insertStmt = dao.tidb.Prepared(_addHistorySQL)
  46. dao.loadBusiness()
  47. go dao.loadBusinessproc()
  48. return
  49. }
  50. // Close close the resource.
  51. func (d *Dao) Close() {
  52. d.redis.Close()
  53. d.tidb.Close()
  54. }
  55. // Ping dao ping
  56. func (d *Dao) Ping(c context.Context) (err error) {
  57. if err = d.tidb.Ping(c); err != nil {
  58. return
  59. }
  60. return d.pingRedis(c)
  61. }
  62. // LoadBusiness .
  63. func (d *Dao) loadBusiness() {
  64. var business []*model.Business
  65. var err error
  66. businessMap := make(map[string]*model.Business)
  67. businessIDMap := make(map[int64]*model.Business)
  68. for {
  69. if business, err = d.QueryBusinesses(context.TODO()); err != nil {
  70. time.Sleep(time.Second)
  71. continue
  72. }
  73. for _, b := range business {
  74. businessMap[b.Name] = b
  75. businessIDMap[b.ID] = b
  76. }
  77. d.BusinessNames = businessMap
  78. d.Businesses = businessIDMap
  79. return
  80. }
  81. }
  82. func (d *Dao) loadBusinessproc() {
  83. for {
  84. time.Sleep(time.Minute * 5)
  85. d.loadBusiness()
  86. }
  87. }