dao.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "net/http"
  7. "time"
  8. "go-common/app/tool/saga/conf"
  9. "go-common/library/cache/memcache"
  10. "go-common/library/cache/redis"
  11. "go-common/library/database/hbase.v2"
  12. "go-common/library/database/orm"
  13. bm "go-common/library/net/http/blademaster"
  14. "github.com/jinzhu/gorm"
  15. "github.com/pkg/errors"
  16. )
  17. // Dao def
  18. type Dao struct {
  19. // cache
  20. httpClient *bm.Client
  21. mysql *gorm.DB
  22. mcMR *memcache.Pool
  23. redis *redis.Pool
  24. hbase *hbase.Client
  25. mcMRRecordExpire int32
  26. }
  27. // New create instance of Dao
  28. func New() (d *Dao) {
  29. d = &Dao{
  30. httpClient: bm.NewClient(conf.Conf.HTTPClient),
  31. mysql: orm.NewMySQL(conf.Conf.ORM),
  32. mcMR: memcache.NewPool(conf.Conf.Memcache.MR),
  33. redis: redis.NewPool(conf.Conf.Redis),
  34. hbase: hbase.NewClient(conf.Conf.HBase.Config),
  35. mcMRRecordExpire: int32(time.Duration(conf.Conf.Memcache.MRRecordExpire) / time.Second),
  36. }
  37. return
  38. }
  39. // Ping dao.
  40. func (d *Dao) Ping(c context.Context) (err error) {
  41. if err = d.pingRedis(c); err != nil {
  42. return
  43. }
  44. if err = d.pingMC(c); err != nil {
  45. return
  46. }
  47. return d.mysql.DB().Ping()
  48. }
  49. // Close dao.
  50. func (d *Dao) Close() {
  51. if d.mcMR != nil {
  52. d.mcMR.Close()
  53. }
  54. if d.redis != nil {
  55. d.redis.Close()
  56. }
  57. if d.mysql != nil {
  58. d.mysql.Close()
  59. }
  60. if d.hbase != nil {
  61. d.hbase.Close()
  62. }
  63. }
  64. func (d *Dao) newRequest(method, url string, v interface{}) (req *http.Request, err error) {
  65. body := &bytes.Buffer{}
  66. if method != http.MethodGet {
  67. if err = json.NewEncoder(body).Encode(v); err != nil {
  68. err = errors.WithStack(err)
  69. return
  70. }
  71. }
  72. if req, err = http.NewRequest(method, url, body); err != nil {
  73. err = errors.WithStack(err)
  74. }
  75. return
  76. }