db_connector.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package database
  2. import (
  3. "eta/eta_mini_ht_api/common/component/config"
  4. "eta/eta_mini_ht_api/common/component/database/dialector"
  5. logger "eta/eta_mini_ht_api/common/component/log"
  6. "eta/eta_mini_ht_api/common/contants"
  7. "gorm.io/gorm"
  8. "os"
  9. "sync"
  10. )
  11. const (
  12. MAIN = "main"
  13. EMAS = "emas"
  14. ETA = "eta"
  15. GL = "gl"
  16. etaDriver = "mysql"
  17. glDriver = "mysql"
  18. )
  19. var (
  20. dbOnce sync.Once
  21. etaDBOnce sync.Once
  22. glDBOnce sync.Once
  23. )
  24. var dbInsts = make(map[string]*gorm.DB)
  25. func Register(name string, dbInst *gorm.DB) {
  26. if dbInst == nil {
  27. panic("数据库不能为空")
  28. }
  29. if _, ok := dbInsts[name]; ok {
  30. panic("当前数据库实例已注册:" + name)
  31. }
  32. dbInsts[name] = dbInst
  33. }
  34. func Select(name string) *gorm.DB {
  35. db := dbInsts[name]
  36. if db == nil {
  37. panic("数据库未初始化")
  38. }
  39. return db
  40. }
  41. func init() {
  42. //初始化主数据库
  43. dbOnce.Do(func() {
  44. dbConfig, ok := config.GetConfig(contants.DATABASE).(*config.DBConfig)
  45. if !ok {
  46. panic("初始化数据库失败,配置文件格式不正确")
  47. }
  48. driver := dbConfig.GetDriver()
  49. dns := dbConfig.GetUrl()
  50. open, err := gorm.Open(dialector.GetGormDial(driver).GetDial(dns), &gorm.Config{})
  51. if err != nil {
  52. logger.Error("初始化数据库失败:%v", err)
  53. os.Exit(0)
  54. }
  55. Register(MAIN, open)
  56. logger.Info("初始化主库数据库成功")
  57. //第三方的数据库
  58. initDataBases()
  59. })
  60. }
  61. func initDataBases() {
  62. initEtaDatabase()
  63. initGLDatabase()
  64. }
  65. func initEtaDatabase() {
  66. etaDBOnce.Do(func() {
  67. etaConfig, ok := config.GetConfig(contants.ETA).(*config.ETAConfig)
  68. if !ok {
  69. panic("初始化eta数据库失败,配置文件格式不正确")
  70. }
  71. dns := etaConfig.GetDBUrl()
  72. open, err := gorm.Open(dialector.GetGormDial(etaDriver).GetDial(dns), &gorm.Config{})
  73. if err != nil {
  74. logger.Error("初始化ETA数据库失败:%v", err)
  75. os.Exit(0)
  76. }
  77. Register(ETA, open)
  78. logger.Info("初始化ETA数据库成功")
  79. })
  80. }
  81. func initGLDatabase() {
  82. glDBOnce.Do(func() {
  83. etaConfig, ok := config.GetConfig(contants.GL).(*config.GLConfig)
  84. if !ok {
  85. panic("初始化钢联数据库失败,配置文件格式不正确")
  86. }
  87. dns := etaConfig.GetDBUrl()
  88. open, err := gorm.Open(dialector.GetGormDial(glDriver).GetDial(dns), &gorm.Config{})
  89. if err != nil {
  90. logger.Error("初始化钢联数据库失败:%v", err)
  91. os.Exit(0)
  92. }
  93. Register(GL, open)
  94. logger.Info("初始化钢联数据库成功")
  95. })
  96. }