dao.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/service/main/push-strategy/conf"
  6. "go-common/library/cache/memcache"
  7. "go-common/library/cache/redis"
  8. xsql "go-common/library/database/sql"
  9. xhttp "go-common/library/net/http/blademaster"
  10. "go-common/library/stat/prom"
  11. )
  12. // Dao .
  13. type Dao struct {
  14. c *conf.Config
  15. db *xsql.DB
  16. redis *redis.Pool
  17. mc *memcache.Pool
  18. httpClient *xhttp.Client
  19. appsStmt *xsql.Stmt
  20. businessesStmt *xsql.Stmt
  21. addTaskStmt *xsql.Stmt
  22. taskStmt *xsql.Stmt
  23. settingsByRangeStmt *xsql.Stmt
  24. maxSettingIDStmt *xsql.Stmt
  25. mcUUIDExpire int32
  26. mcCDExpire int32
  27. redisLimitDayExpire int32
  28. }
  29. // New new dao.
  30. func New(c *conf.Config) (d *Dao) {
  31. d = &Dao{
  32. c: c,
  33. db: xsql.NewMySQL(c.MySQL),
  34. httpClient: xhttp.NewClient(c.HTTPClient),
  35. redis: redis.NewPool(c.Redis.Config),
  36. mc: memcache.NewPool(c.Memcache.Config),
  37. mcUUIDExpire: int32(time.Duration(c.Memcache.UUIDExpire) / time.Second),
  38. mcCDExpire: int32(time.Duration(c.Memcache.CDExpire) / time.Second),
  39. redisLimitDayExpire: int32(time.Duration(c.Redis.LimitDayExpire) / time.Second),
  40. }
  41. d.appsStmt = d.db.Prepared(_appsSQL)
  42. d.businessesStmt = d.db.Prepared(_businessesSQL)
  43. d.addTaskStmt = d.db.Prepared(_addTaskSQL)
  44. d.taskStmt = d.db.Prepared(_taskSQL)
  45. d.settingsByRangeStmt = d.db.Prepared(_settingsByRangeSQL)
  46. d.maxSettingIDStmt = d.db.Prepared(_maxSettingIDSQL)
  47. return
  48. }
  49. // PromError prom error
  50. func PromError(name string) {
  51. prom.BusinessErrCount.Incr(name)
  52. }
  53. // PromInfo add prom info
  54. func PromInfo(name string) {
  55. prom.BusinessInfoCount.Incr(name)
  56. }
  57. // BeginTx begin transaction.
  58. func (d *Dao) BeginTx(ctx context.Context) (*xsql.Tx, error) {
  59. return d.db.Begin(ctx)
  60. }
  61. // Ping .
  62. func (d *Dao) Ping(ctx context.Context) (err error) {
  63. if err = d.pingRedis(ctx); err != nil {
  64. return
  65. }
  66. if err = d.pingMC(ctx); err != nil {
  67. return
  68. }
  69. return d.db.Ping(ctx)
  70. }
  71. // Close .
  72. func (d *Dao) Close() {
  73. d.mc.Close()
  74. d.redis.Close()
  75. d.db.Close()
  76. }