dao.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package dao
  2. import (
  3. "context"
  4. "time"
  5. "go-common/app/admin/main/reply/conf"
  6. "go-common/library/cache/memcache"
  7. "go-common/library/cache/redis"
  8. es "go-common/library/database/elastic"
  9. "go-common/library/database/sql"
  10. bm "go-common/library/net/http/blademaster"
  11. "go-common/library/queue/databus"
  12. )
  13. // Dao dao.
  14. type Dao struct {
  15. c *conf.Config
  16. // db
  17. db *sql.DB
  18. dbSlave *sql.DB
  19. // cache
  20. redis *redis.Pool
  21. redisExpire int32
  22. mc *memcache.Pool
  23. mcExpire int32
  24. // http
  25. httpClient *bm.Client
  26. // databus
  27. eventBus *databus.Databus
  28. // new databus stats
  29. statsBus *databus.Databus
  30. statsTypes map[int32]string
  31. es *es.Elastic
  32. }
  33. // New new a dao and return.
  34. func New(c *conf.Config) (d *Dao) {
  35. d = &Dao{
  36. c: c,
  37. // db
  38. db: sql.NewMySQL(c.DB.Reply),
  39. dbSlave: sql.NewMySQL(c.DB.ReplySlave),
  40. // cache
  41. redis: redis.NewPool(c.Redis.Config),
  42. redisExpire: int32(time.Duration(c.Redis.Expire) / time.Second),
  43. mc: memcache.NewPool(c.Memcache.Config),
  44. mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
  45. // http
  46. httpClient: bm.NewClient(c.HTTPClient),
  47. // databus
  48. eventBus: databus.New(c.Databus.Event),
  49. es: es.NewElastic(c.Es),
  50. }
  51. // new databus stats
  52. d.statsTypes = make(map[int32]string)
  53. for name, typ := range c.StatTypes {
  54. d.statsTypes[typ] = name
  55. }
  56. d.statsBus = databus.New(c.Databus.Stats)
  57. return
  58. }
  59. func hit(id int64) int64 {
  60. return id % 200
  61. }
  62. // BeginTran begin transaction.
  63. func (d *Dao) BeginTran(c context.Context) (*sql.Tx, error) {
  64. return d.db.Begin(c)
  65. }
  66. // Ping ping resouces is ok.
  67. func (d *Dao) Ping(c context.Context) (err error) {
  68. if err = d.db.Ping(c); err != nil {
  69. return
  70. }
  71. return d.pingMC(c)
  72. }