|
@@ -14,8 +14,9 @@ import (
|
|
|
)
|
|
|
|
|
|
// DB2.0 数据库连接 gorm2.0
|
|
|
-var DB *gorm.DB //gs 数据库
|
|
|
+var DBS map[string]*gorm.DB //gs 数据库
|
|
|
type DbConfig struct {
|
|
|
+ Name string
|
|
|
Host string
|
|
|
Port string
|
|
|
User string
|
|
@@ -24,27 +25,35 @@ type DbConfig struct {
|
|
|
Charset string
|
|
|
}
|
|
|
|
|
|
-func GetDB(c *gin.Context) *gorm.DB {
|
|
|
+func GetDB(c *gin.Context, dbName ...string) *gorm.DB {
|
|
|
v, _ := c.Get("X-Span-ID")
|
|
|
spanId := fmt.Sprintf("%v", v)
|
|
|
ctx := context.WithValue(context.Background(), "X-Span-ID", spanId)
|
|
|
- return DB.WithContext(ctx)
|
|
|
+ d := "one"
|
|
|
+ if len(dbName) != 0 {
|
|
|
+ d = dbName[0]
|
|
|
+ }
|
|
|
+ return DBS[d].WithContext(ctx)
|
|
|
+}
|
|
|
+
|
|
|
+func InitDBS(env string, conf []DbConfig) {
|
|
|
+ DBS = map[string]*gorm.DB{}
|
|
|
+ if len(conf) == 1 {
|
|
|
+ conf[0].Name = "one"
|
|
|
+ }
|
|
|
+ for _, config := range conf {
|
|
|
+ InitDB(env, config)
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
func InitDB(env string, conf DbConfig) {
|
|
|
- //dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
|
|
|
- //newLogger := logger.New(
|
|
|
- // //zap.NewStdLog(),
|
|
|
- // log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
|
|
|
- // logger.Config{
|
|
|
- // SlowThreshold: 200 * time.Millisecond, // Slow SQL threshold
|
|
|
- // LogLevel: logger.Info, // Log level
|
|
|
- // IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
|
|
|
- // Colorful: false, // Disable color
|
|
|
- // },
|
|
|
- //)
|
|
|
+ if conf.Name == "" {
|
|
|
+ DBS = nil
|
|
|
+ fmt.Println("db name 错误")
|
|
|
+ return
|
|
|
+ }
|
|
|
if conf.Host == "" {
|
|
|
- DB = nil
|
|
|
+ DBS = nil
|
|
|
fmt.Println("未配置Db连接")
|
|
|
return
|
|
|
}
|
|
@@ -64,7 +73,7 @@ func InitDB(env string, conf DbConfig) {
|
|
|
fmt.Println(err.Error())
|
|
|
os.Exit(-1)
|
|
|
}
|
|
|
- DB = db
|
|
|
+ DBS[conf.Name] = db
|
|
|
} else {
|
|
|
logger2 := lxzap.NewGormZap(zap.L())
|
|
|
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
|
|
@@ -78,7 +87,7 @@ func InitDB(env string, conf DbConfig) {
|
|
|
fmt.Println(err.Error())
|
|
|
os.Exit(-1)
|
|
|
}
|
|
|
- DB = db
|
|
|
+ DBS[conf.Name] = db
|
|
|
}
|
|
|
//db.AutoMigrate(TaskData{}, Task{}, Version{})
|
|
|
}
|