dao.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package dao
  2. import (
  3. "context"
  4. "net/http"
  5. "time"
  6. "go-common/app/admin/openplatform/sug/conf"
  7. "go-common/library/cache/redis"
  8. "go-common/library/database/sql"
  9. "go-common/library/log"
  10. xhttp "go-common/library/net/http/blademaster"
  11. elastic "gopkg.in/olivere/elastic.v5"
  12. )
  13. // Dao dao
  14. type Dao struct {
  15. c *conf.Config
  16. redis *redis.Pool
  17. es *elastic.Client
  18. client *http.Client
  19. xclient *xhttp.Client
  20. dbMall *sql.DB
  21. dbTicket *sql.DB
  22. }
  23. // New init redis,es
  24. func New(c *conf.Config) (dao *Dao) {
  25. dao = &Dao{
  26. c: c,
  27. redis: redis.NewPool(c.Redis),
  28. xclient: xhttp.NewClient(c.HTTPClient),
  29. client: &http.Client{Timeout: time.Second * 5},
  30. dbMall: sql.NewMySQL(c.DB.MallDB),
  31. dbTicket: sql.NewMySQL(c.DB.TicketDB),
  32. }
  33. es, err := elastic.NewClient(
  34. elastic.SetURL(c.Es.Addr...),
  35. )
  36. if err != nil {
  37. panic(err)
  38. }
  39. dao.es = es
  40. return
  41. }
  42. // Close close the resource.
  43. func (d *Dao) Close() {
  44. d.redis.Close()
  45. }
  46. // Ping dao ping
  47. func (d *Dao) Ping(c context.Context) (err error) {
  48. if err = d.dbTicket.Ping(c); err != nil {
  49. log.Error("Ping ticket DB error(%v)", err)
  50. return
  51. }
  52. if err = d.dbMall.Ping(c); err != nil {
  53. log.Error("Ping mall DB error(%v)", err)
  54. return
  55. }
  56. if err = d.pingESCluster(c); err != nil {
  57. log.Error("es:ping", "ping %v", err)
  58. return
  59. }
  60. redisConn := d.redis.Get(c)
  61. defer redisConn.Close()
  62. if _, err = redisConn.Do("SET", "ping", "pong"); err != nil {
  63. redisConn.Close()
  64. log.Error("redis.SET error(%v)", err)
  65. return
  66. }
  67. return
  68. }
  69. // pingEsCluster ping es cluster
  70. func (d *Dao) pingESCluster(ctx context.Context) (err error) {
  71. _, _, err = d.es.Ping(d.c.Es.Addr[0]).Do(ctx)
  72. if err != nil {
  73. log.Error("Es:Ping", "%s:Ping error(%v)", d.c.Es.Addr[0], err)
  74. return
  75. }
  76. return
  77. }