123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package init_serve
- import (
- "eta/eta_bridge/global"
- "eta/eta_bridge/services/binlog"
- "fmt"
- "gorm.io/driver/mysql"
- "gorm.io/gorm"
- "gorm.io/gorm/logger"
- "io"
- "log"
- "os"
- "time"
- )
- // Mysql 数据库初始化
- 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) //binlog日志,记录到文件中去
- 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, //慢sql :200ms
- LogLevel: logger.Info, //记录的日志类型,info代表所有信息都记录
- IgnoreRecordNotFoundError: true, //是否忽略找不到数据错误信息(只是日志记录记录成err还是普通的输出的区别,并不影响业务代码中的:找不到数据行error)
- 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
- }
- // SetMaxIdleConns 设置空闲连接池中连接的最大数量
- sqlDB.SetMaxIdleConns(conf.MaxIdleConns)
- // SetMaxOpenConns 设置打开数据库连接的最大数量。
- sqlDB.SetMaxOpenConns(conf.MaxOpenConns)
- // SetConnMaxLifetime 设置了连接可复用的最大时间。
- //sqlDB.SetConnMaxLifetime(time.Hour)
- }
- //全局赋值数据库链接
- global.MYSQL = mysqlMap
- // 开启mysql binlog监听
- if mysqlConf.Binlog.IsListen {
- go binlog.ListenMysql()
- }
- fmt.Println("mysql init end")
- }
|