12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package init_serve
- import (
- "fmt"
- "gorm.io/driver/mysql"
- "gorm.io/gorm"
- "gorm.io/gorm/logger"
- "hongze/hongze_yb/global"
- "io"
- "log"
- "os"
- "time"
- )
- func Mysql() {
- mysqlConf := global.CONFIG.Mysql
- if len(mysqlConf.List) <= 0 {
- global.LOG.Error("mysql链接未配置")
- panic(fmt.Errorf("mysql链接未配置"))
- }
-
- logWriter := io.MultiWriter(global.MYSQL_LOG)
- if global.CONFIG.Mysql.Stdout {
- logWriter = io.MultiWriter(global.MYSQL_LOG, os.Stdout)
- }
- newLogger := logger.New(log.New(logWriter, "\r\n", log.LstdFlags), logger.Config{
- SlowThreshold: 200 * time.Millisecond,
- LogLevel: logger.Info,
- IgnoreRecordNotFoundError: true,
- Colorful: true,
- })
- mysqlMap := make(map[string]*gorm.DB)
- for _, conf := range mysqlConf.List {
- dsn := conf.Dsn
- db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
- Logger: newLogger,
- })
- if err != nil {
- global.LOG.Errorf("mysql 启动异常,数据库:", conf.AliasName, ";Err:", err)
- panic(fmt.Errorf("mysql 启动异常,数据库:", conf.AliasName, "Err:%s", err))
- }
-
- sqlDB, err := db.DB()
- if err != nil {
- global.LOG.Errorf("mysql 创建连接池失败,数据库:", conf.AliasName, ";Err:", err)
- panic(fmt.Errorf("mysql 创建连接池失败,数据库:", conf.AliasName, "Err:%s", err))
- }
- mysqlMap[conf.AliasName] = db
-
- if mysqlConf.DefaultDsnAliasName == conf.AliasName {
- global.DEFAULT_MYSQL = db
- }
-
- sqlDB.SetMaxIdleConns(conf.MaxIdleConns)
-
- sqlDB.SetMaxOpenConns(conf.MaxOpenConns)
-
-
- }
-
- global.MYSQL = mysqlMap
- }
|