dao.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package mcndao
  2. import (
  3. "context"
  4. "fmt"
  5. "runtime"
  6. "time"
  7. "go-common/app/interface/main/mcn/conf"
  8. "go-common/app/interface/main/mcn/dao/global"
  9. "go-common/library/cache/memcache"
  10. "go-common/library/sync/pipeline/fanout"
  11. "github.com/bluele/gcache"
  12. "github.com/jinzhu/gorm"
  13. )
  14. // Dao dao
  15. type Dao struct {
  16. c *conf.Config
  17. mc *memcache.Pool
  18. mcndb *gorm.DB
  19. //cache tool
  20. cache *fanout.Fanout
  21. mcnSignExpire int32
  22. mcnDataExpire int32
  23. localcache gcache.Cache
  24. }
  25. // New init mysql db
  26. func New(c *conf.Config, localcache gcache.Cache) (dao *Dao) {
  27. dao = &Dao{
  28. c: c,
  29. mc: global.GetMc(),
  30. // cache worker
  31. cache: fanout.New("cache", fanout.Worker(runtime.NumCPU()), fanout.Buffer(1024)),
  32. mcnSignExpire: int32(time.Duration(c.Memcache.McnSignCacheExpire) / time.Second),
  33. mcnDataExpire: int32(time.Duration(c.Memcache.McnDataCacheExpire) / time.Second),
  34. localcache: localcache,
  35. }
  36. if localcache == nil {
  37. dao.localcache = gcache.New(c.RankCache.Size).Simple().Build()
  38. }
  39. if dao.mcnDataExpire == 0 {
  40. dao.mcnDataExpire = 3600
  41. }
  42. if dao.mcnSignExpire == 0 {
  43. dao.mcnSignExpire = 3600
  44. }
  45. var err error
  46. dao.mcndb, err = gorm.Open("mysql", c.MCNorm.DSN)
  47. if err != nil {
  48. panic(fmt.Errorf("db connect fail, err=%s", err))
  49. }
  50. dao.mcndb.LogMode(c.Other.Debug)
  51. return
  52. }
  53. // Close close the resource.
  54. func (d *Dao) Close() {
  55. d.cache.Close()
  56. d.mc.Close()
  57. d.mcndb.Close()
  58. }
  59. // Ping dao ping
  60. func (d *Dao) Ping(c context.Context) error {
  61. return nil
  62. }
  63. //GetMcnDB get mcn db
  64. func (d *Dao) GetMcnDB() *gorm.DB {
  65. return d.mcndb
  66. }