dao.go 2.2 KB

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