dao.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package dao
  2. import (
  3. "context"
  4. "math/rand"
  5. "time"
  6. "go-common/app/service/main/spy/conf"
  7. "go-common/library/cache/memcache"
  8. "go-common/library/cache/redis"
  9. "go-common/library/database/sql"
  10. bm "go-common/library/net/http/blademaster"
  11. "go-common/library/queue/databus"
  12. )
  13. // Dao event dao def.
  14. type Dao struct {
  15. c *conf.Config
  16. // db
  17. db *sql.DB
  18. // mc
  19. mcUser *memcache.Pool
  20. mcUserExpire int32
  21. // redis
  22. redis *redis.Pool
  23. expire int
  24. verifyExpire int
  25. // http client
  26. httpClient *bm.Client
  27. auditInfoURI string
  28. // databus for spy score change
  29. dbScoreChange *databus.Databus
  30. r *rand.Rand
  31. }
  32. // New create instance of dao and return.
  33. func New(c *conf.Config) (d *Dao) {
  34. d = &Dao{
  35. c: c,
  36. // db
  37. db: sql.NewMySQL(c.DB.Spy),
  38. // mc
  39. mcUser: memcache.NewPool(c.Memcache.User),
  40. mcUserExpire: int32(time.Duration(c.Memcache.UserExpire) / time.Second),
  41. // redis
  42. redis: redis.NewPool(c.Redis.Config),
  43. expire: int(time.Duration(c.Redis.Expire) / time.Second),
  44. verifyExpire: int(time.Duration(c.Redis.VerifyCdTimes) / time.Second),
  45. // http client
  46. httpClient: bm.NewClient(c.HTTPClient),
  47. auditInfoURI: c.Account + _auditInfo,
  48. // databus
  49. dbScoreChange: databus.New(c.DBScoreChange),
  50. r: rand.New(rand.NewSource(time.Now().Unix())),
  51. }
  52. if conf.Conf.Property.UserInfoShard <= 0 {
  53. panic("conf.Conf.Property.UserInfoShard <= 0")
  54. }
  55. if conf.Conf.Property.HistoryShard <= 0 {
  56. panic("conf.Conf.Property.HistoryShard <= 0")
  57. }
  58. return
  59. }
  60. // Ping check db health.
  61. func (d *Dao) Ping(c context.Context) (err error) {
  62. if err = d.pingMC(c); err != nil {
  63. return
  64. }
  65. if err = d.PingRedis(c); err != nil {
  66. return
  67. }
  68. return d.db.Ping(c)
  69. }
  70. // Close close all db connections.
  71. func (d *Dao) Close() {
  72. if d.mcUser != nil {
  73. d.mcUser.Close()
  74. }
  75. if d.redis != nil {
  76. d.redis.Close()
  77. }
  78. if d.db != nil {
  79. d.db.Close()
  80. }
  81. }