支持多个db

This commit is contained in:
liuchangshun 2024-03-06 14:41:53 +08:00
parent 32e3d99d37
commit 4fb99540c5
2 changed files with 28 additions and 19 deletions

View File

@ -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{})
}

View File

@ -16,7 +16,7 @@ import (
"time"
)
func Run(env string, port string, fun func(), r func(router *gin.Engine), zapConfig lxzap.ZapLogConfig, dbConf lxDb.DbConfig, redisConf lxDb.RedisConfig) {
func Run(env string, port string, fun func(), r func(router *gin.Engine), zapConfig lxzap.ZapLogConfig, dbConf []lxDb.DbConfig, redisConf lxDb.RedisConfig) {
_ = lxlog.InitLog()
err := lxzap.InitZapLogger(zapConfig)
if err != nil {
@ -29,7 +29,7 @@ func Run(env string, port string, fun func(), r func(router *gin.Engine), zapCon
} else {
app.Use(lxzap.GinLogger(), lxzap.GinRecovery(true))
}
lxDb.InitDB(env, dbConf)
lxDb.InitDBS(env, dbConf)
lxDb.InitRedis(redisConf)
lxLock.InitRedis(redisConf)
fun()