dao.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/service/main/favorite/conf"
  6. "go-common/library/cache/memcache"
  7. "go-common/library/cache/redis"
  8. "go-common/library/database/sql"
  9. httpx "go-common/library/net/http/blademaster"
  10. "go-common/library/queue/databus"
  11. )
  12. // Dao favorite dao.
  13. type Dao struct {
  14. db *sql.DB
  15. dbRead *sql.DB
  16. dbPush *sql.DB
  17. mc *memcache.Pool
  18. redis *redis.Pool
  19. redisExpire int
  20. mcExpire int32
  21. jobDatabus *databus.Databus
  22. httpClient *httpx.Client
  23. }
  24. // New a dao and return.
  25. func New(c *conf.Config) (d *Dao) {
  26. d = &Dao{
  27. // db
  28. db: sql.NewMySQL(c.MySQL.Fav),
  29. dbRead: sql.NewMySQL(c.MySQL.Read),
  30. dbPush: sql.NewMySQL(c.MySQL.Push),
  31. // redis
  32. redis: redis.NewPool(c.Redis.Config),
  33. redisExpire: int(time.Duration(c.Redis.Expire) / time.Second),
  34. // memcache
  35. mc: memcache.NewPool(c.Memcache.Config),
  36. mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
  37. // databus
  38. jobDatabus: databus.New(c.JobDatabus),
  39. // httpclient
  40. httpClient: httpx.NewClient(c.HTTPClient),
  41. }
  42. return
  43. }
  44. // Close close all connection.
  45. func (d *Dao) Close() {
  46. if d.db != nil {
  47. d.db.Close()
  48. }
  49. if d.dbRead != nil {
  50. d.dbRead.Close()
  51. }
  52. if d.redis != nil {
  53. d.redis.Close()
  54. }
  55. if d.mc != nil {
  56. d.mc.Close()
  57. }
  58. if d.jobDatabus != nil {
  59. d.jobDatabus.Close()
  60. }
  61. }
  62. // BeginTran crate a *sql.Tx for database transaction.
  63. func (d *Dao) BeginTran(c context.Context) (*sql.Tx, error) {
  64. return d.db.Begin(c)
  65. }
  66. // Ping check connection used in dao
  67. func (d *Dao) Ping(c context.Context) (err error) {
  68. if err = d.pingRedis(c); err != nil {
  69. return
  70. }
  71. if err = d.pingMC(c); err != nil {
  72. return
  73. }
  74. err = d.pingMySQL(c)
  75. return
  76. }