dao.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "net/http"
  7. "time"
  8. "go-common/app/admin/ep/marthe/conf"
  9. "go-common/library/cache/memcache"
  10. "go-common/library/database/orm"
  11. "go-common/library/log"
  12. xhttp "go-common/library/net/http/blademaster"
  13. "go-common/library/sync/pipeline/fanout"
  14. "github.com/jinzhu/gorm"
  15. "gopkg.in/gomail.v2"
  16. )
  17. const _wildcards = "%"
  18. // Dao dao
  19. type Dao struct {
  20. c *conf.Config
  21. httpClient *xhttp.Client
  22. email *gomail.Dialer
  23. db *gorm.DB
  24. cache *fanout.Fanout
  25. mc *memcache.Pool
  26. expire int32
  27. }
  28. // New init mysql db
  29. func New(c *conf.Config) (dao *Dao) {
  30. dao = &Dao{
  31. c: c,
  32. email: gomail.NewDialer(c.Mail.Host, c.Mail.Port, c.Mail.Username, c.Mail.Password),
  33. httpClient: xhttp.NewClient(c.HTTPClient),
  34. cache: fanout.New("mcCache", fanout.Worker(1), fanout.Buffer(1024)),
  35. mc: memcache.NewPool(c.Memcache.Config),
  36. expire: int32(time.Duration(c.Memcache.Expire) / time.Second),
  37. }
  38. if c.ORM != nil {
  39. dao.db = orm.NewMySQL(c.ORM)
  40. }
  41. return
  42. }
  43. // Close close the resource.
  44. func (d *Dao) Close() {
  45. if d.db != nil {
  46. d.db.Close()
  47. }
  48. if d.mc != nil {
  49. d.mc.Close()
  50. }
  51. }
  52. // Ping verify server is ok.
  53. func (d *Dao) Ping(c context.Context) (err error) {
  54. if d.db != nil {
  55. if err = d.db.DB().Ping(); err != nil {
  56. log.Info("dao.cloudDB.Ping() error(%v)", err)
  57. }
  58. }
  59. return
  60. }
  61. func (d *Dao) newRequest(method, url string, v interface{}) (req *http.Request, err error) {
  62. body := &bytes.Buffer{}
  63. if method != http.MethodGet {
  64. if err = json.NewEncoder(body).Encode(v); err != nil {
  65. log.Error("json encode value(%s) err(%v) ", v, err)
  66. return
  67. }
  68. }
  69. if req, err = http.NewRequest(method, url, body); err != nil {
  70. log.Error("http new request url(%s) err(%v)", url, err)
  71. }
  72. return
  73. }
  74. // cacheSave cache Save.
  75. func (d *Dao) cacheSave(c context.Context, cacheItem *memcache.Item) {
  76. var f = func(ctx context.Context) {
  77. var (
  78. conn = d.mc.Get(c)
  79. err error
  80. )
  81. defer conn.Close()
  82. if err = conn.Set(cacheItem); err != nil {
  83. log.Error("Add Cache conn.Set(%s) error(%v)", cacheItem.Key, err)
  84. }
  85. }
  86. if err := d.cache.Do(c, f); err != nil {
  87. log.Error("ReleaseName cache save err(%v)", err)
  88. }
  89. }