dao.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/job/main/vip/conf"
  6. "go-common/library/cache/memcache"
  7. "go-common/library/cache/redis"
  8. "go-common/library/database/sql"
  9. bm "go-common/library/net/http/blademaster"
  10. "go-common/library/stat/prom"
  11. )
  12. // Dao struct info of Dao.
  13. type Dao struct {
  14. // mysql
  15. db *sql.DB
  16. oldDb *sql.DB
  17. // http
  18. client *bm.Client
  19. // conf
  20. c *conf.Config
  21. // memcache
  22. mc *memcache.Pool
  23. mcExpire int32
  24. //redis pool
  25. redis *redis.Pool
  26. redisExpire int32
  27. errProm *prom.Prom
  28. frozenExpire int32
  29. }
  30. // New new a Dao and return.
  31. func New(c *conf.Config) (d *Dao) {
  32. d = &Dao{
  33. // conf
  34. c: c,
  35. // mc
  36. mc: memcache.NewPool(c.Memcache.Config),
  37. mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
  38. // redis
  39. redis: redis.NewPool(c.Redis.Config),
  40. redisExpire: int32(time.Duration(c.Redis.Expire) / time.Second),
  41. // db
  42. db: sql.NewMySQL(c.NewMysql),
  43. oldDb: sql.NewMySQL(c.OldMysql),
  44. // http client
  45. client: bm.NewClient(c.HTTPClient),
  46. errProm: prom.BusinessErrCount,
  47. frozenExpire: int32(time.Duration(c.Property.FrozenExpire) / time.Second),
  48. }
  49. return
  50. }
  51. // Ping ping health of db.
  52. func (d *Dao) Ping(c context.Context) (err error) {
  53. return d.db.Ping(c)
  54. }
  55. // Close close connections of mc, redis, db.
  56. func (d *Dao) Close() {
  57. if d.db != nil {
  58. d.db.Close()
  59. }
  60. if d.redis != nil {
  61. d.redis.Close()
  62. }
  63. }
  64. //StartTx start tx
  65. func (d *Dao) StartTx(c context.Context) (tx *sql.Tx, err error) {
  66. if d.db != nil {
  67. tx, err = d.db.Begin(c)
  68. }
  69. return
  70. }