dao.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/service/main/coupon/conf"
  6. "go-common/library/cache/memcache"
  7. xsql "go-common/library/database/sql"
  8. bm "go-common/library/net/http/blademaster"
  9. "go-common/library/stat/prom"
  10. )
  11. // Dao dao
  12. type Dao struct {
  13. c *conf.Config
  14. mc *memcache.Pool
  15. db *xsql.DB
  16. errProm *prom.Prom
  17. mcExpire int32
  18. prizeExpire int32
  19. client *bm.Client
  20. }
  21. // New init mysql db
  22. func New(c *conf.Config) (dao *Dao) {
  23. dao = &Dao{
  24. c: c,
  25. mc: memcache.NewPool(c.Memcache.Config),
  26. db: xsql.NewMySQL(c.MySQL),
  27. errProm: prom.BusinessErrCount,
  28. mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
  29. prizeExpire: int32(time.Duration(c.Memcache.PrizeExpire) / time.Second),
  30. client: bm.NewClient(c.HTTPClient),
  31. }
  32. return
  33. }
  34. // Close close the resource.
  35. func (d *Dao) Close() {
  36. d.mc.Close()
  37. d.db.Close()
  38. }
  39. // Ping dao ping
  40. func (d *Dao) Ping(c context.Context) (err error) {
  41. if err = d.db.Ping(c); err != nil {
  42. d.errProm.Incr("ping_db")
  43. return
  44. }
  45. err = d.pingMC(c)
  46. return
  47. }
  48. // pingMc ping
  49. func (d *Dao) pingMC(c context.Context) (err error) {
  50. conn := d.mc.Get(c)
  51. defer conn.Close()
  52. item := memcache.Item{Key: "ping", Value: []byte{1}, Expiration: d.mcExpire}
  53. return conn.Set(&item)
  54. }