123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- package database
- import (
- "eta/eta_mini_ht_api/common/component/config"
- "eta/eta_mini_ht_api/common/component/database/dialector"
- logger "eta/eta_mini_ht_api/common/component/log"
- "eta/eta_mini_ht_api/common/contants"
- "gorm.io/gorm"
- "os"
- "sync"
- )
- const (
- MAIN = "main"
- EMAS = "emas"
- ETA = "eta"
- GL = "gl"
- etaDriver = "mysql"
- glDriver = "mysql"
- )
- var (
- dbOnce sync.Once
- etaDBOnce sync.Once
- glDBOnce sync.Once
- )
- var dbInsts = make(map[string]*gorm.DB)
- func Register(name string, dbInst *gorm.DB) {
- if dbInst == nil {
- panic("数据库不能为空")
- }
- if _, ok := dbInsts[name]; ok {
- panic("当前数据库实例已注册:" + name)
- }
- dbInsts[name] = dbInst
- }
- func Select(name string) *gorm.DB {
- db := dbInsts[name]
- if db == nil {
- panic("数据库未初始化")
- }
- return db
- }
- func init() {
- //初始化主数据库
- dbOnce.Do(func() {
- dbConfig, ok := config.GetConfig(contants.DATABASE).(*config.DBConfig)
- if !ok {
- panic("初始化数据库失败,配置文件格式不正确")
- }
- driver := dbConfig.GetDriver()
- dns := dbConfig.GetUrl()
- open, err := gorm.Open(dialector.GetGormDial(driver).GetDial(dns), &gorm.Config{})
- if err != nil {
- logger.Error("初始化数据库失败:%v", err)
- os.Exit(0)
- }
- Register(MAIN, open)
- logger.Info("初始化主库数据库成功")
- //第三方的数据库
- initDataBases()
- })
- }
- func initDataBases() {
- initEtaDatabase()
- initGLDatabase()
- }
- func initEtaDatabase() {
- etaDBOnce.Do(func() {
- etaConfig, ok := config.GetConfig(contants.ETA).(*config.ETAConfig)
- if !ok {
- panic("初始化eta数据库失败,配置文件格式不正确")
- }
- dns := etaConfig.GetDBUrl()
- open, err := gorm.Open(dialector.GetGormDial(etaDriver).GetDial(dns), &gorm.Config{})
- if err != nil {
- logger.Error("初始化ETA数据库失败:%v", err)
- os.Exit(0)
- }
- Register(ETA, open)
- logger.Info("初始化ETA数据库成功")
- })
- }
- func initGLDatabase() {
- glDBOnce.Do(func() {
- etaConfig, ok := config.GetConfig(contants.GL).(*config.GLConfig)
- if !ok {
- panic("初始化钢联数据库失败,配置文件格式不正确")
- }
- dns := etaConfig.GetDBUrl()
- open, err := gorm.Open(dialector.GetGormDial(glDriver).GetDial(dns), &gorm.Config{})
- if err != nil {
- logger.Error("初始化钢联数据库失败:%v", err)
- os.Exit(0)
- }
- Register(GL, open)
- logger.Info("初始化钢联数据库成功")
- })
- }
|