dao.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/net/http/blademaster"
  6. "math/rand"
  7. "time"
  8. "go-common/app/service/live/resource/conf"
  9. "go-common/app/service/live/resource/lrucache"
  10. "go-common/library/database/orm"
  11. xsql "go-common/library/database/sql"
  12. "github.com/jinzhu/gorm"
  13. )
  14. const (
  15. _prefixResource = "live:res:"
  16. _prefixLiveCheck = "live:check:"
  17. _prefixConf = "live:conf:"
  18. )
  19. func cacheResourceKey(typ string, platform string, build int64) string {
  20. return fmt.Sprintf("%s:%s:%s:%d", _prefixResource, typ, platform, build)
  21. }
  22. func cacheLiveCheckKey(platform, system, mobile string) string {
  23. return fmt.Sprintf("%s:%s:%s:%s", _prefixLiveCheck, platform, system, mobile)
  24. }
  25. func cacheConfKey(key string) string {
  26. return fmt.Sprintf("%s:%s", _prefixConf, key)
  27. }
  28. // Dao dao
  29. type Dao struct {
  30. c *conf.Config
  31. db *xsql.DB
  32. rsDB *gorm.DB
  33. rsDBReader *gorm.DB
  34. sCache []*lrucache.SyncCache
  35. client *blademaster.Client
  36. }
  37. // New init mysql db
  38. func New(c *conf.Config) (dao *Dao) {
  39. if c.CacheCapacity <= 0 {
  40. c.CacheCapacity = 100
  41. }
  42. if c.CacheBucket <= 0 {
  43. c.CacheBucket = 100
  44. }
  45. if c.CacheInstCnt <= 0 {
  46. c.CacheInstCnt = 10
  47. }
  48. if c.CacheTimeout <= 0 {
  49. c.CacheTimeout = 60
  50. }
  51. sCache := make([]*lrucache.SyncCache, c.CacheInstCnt)
  52. for i := range sCache {
  53. sCache[i] = lrucache.NewSyncCache(c.CacheCapacity, c.CacheBucket, c.CacheTimeout)
  54. }
  55. dao = &Dao{
  56. c: c,
  57. db: xsql.NewMySQL(c.MySQL),
  58. rsDB: orm.NewMySQL(c.DB.Resource),
  59. rsDBReader: orm.NewMySQL(c.DB.ResourceReader),
  60. sCache: sCache,
  61. client: blademaster.NewClient(c.HttpClient),
  62. }
  63. rand.Seed(time.Now().UnixNano())
  64. return
  65. }
  66. // mysql log
  67. func (d *Dao) initORM() {
  68. d.rsDB.LogMode(true)
  69. d.rsDB.LogMode(true)
  70. }
  71. // Close close the resource.
  72. func (d *Dao) Close() {
  73. d.db.Close()
  74. d.rsDB.Close()
  75. d.rsDBReader.Close()
  76. return
  77. }
  78. // Ping dao ping
  79. func (d *Dao) Ping(c context.Context) (err error) {
  80. // TODO: if you need use mc,redis, please add
  81. if err = d.db.Ping(c); err != nil {
  82. return
  83. }
  84. return
  85. //return d.pingRedis(c)
  86. }