dao.go 2.2 KB

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