mysql.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package init_serve
  2. import (
  3. "eta_gn/eta_bridge/global"
  4. "eta_gn/eta_bridge/services/binlog"
  5. "fmt"
  6. "gorm.io/driver/mysql"
  7. "gorm.io/gorm"
  8. "gorm.io/gorm/logger"
  9. "io"
  10. "log"
  11. "os"
  12. "time"
  13. )
  14. func Mysql() {
  15. mysqlConf := global.CONFIG.Mysql
  16. if len(mysqlConf.List) <= 0 {
  17. global.LOG.Error("mysql链接未配置")
  18. panic(fmt.Errorf("mysql链接未配置"))
  19. }
  20. logWriter := io.MultiWriter(global.MYSQL_LOG) //binlog日志,记录到文件中去
  21. if global.CONFIG.Mysql.Stdout {
  22. logWriter = io.MultiWriter(global.MYSQL_LOG, os.Stdout)
  23. }
  24. newLogger := logger.New(log.New(logWriter, "\r\n", log.LstdFlags), logger.Config{
  25. SlowThreshold: 200 * time.Millisecond, //慢sql :200ms
  26. LogLevel: logger.Info, //记录的日志类型,info代表所有信息都记录
  27. IgnoreRecordNotFoundError: true, //是否忽略找不到数据错误信息(只是日志记录记录成err还是普通的输出的区别,并不影响业务代码中的:找不到数据行error)
  28. Colorful: true, //是否颜色输出
  29. })
  30. mysqlMap := make(map[string]*gorm.DB)
  31. for _, conf := range mysqlConf.List {
  32. dsn := conf.Dsn
  33. db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
  34. Logger: newLogger,
  35. })
  36. if err != nil {
  37. global.LOG.Errorf("mysql 启动异常,数据库:", conf.AliasName, ";Err:", err)
  38. panic(fmt.Errorf("mysql 启动异常,数据库:", conf.AliasName, "Err:%s", err))
  39. }
  40. sqlDB, err := db.DB()
  41. if err != nil {
  42. global.LOG.Errorf("mysql 创建连接池失败,数据库:", conf.AliasName, ";Err:", err)
  43. panic(fmt.Errorf("mysql 创建连接池失败,数据库:", conf.AliasName, "Err:%s", err))
  44. }
  45. mysqlMap[conf.AliasName] = db
  46. if mysqlConf.DefaultDsnAliasName == conf.AliasName {
  47. global.DEFAULT_MYSQL = db
  48. }
  49. sqlDB.SetMaxIdleConns(conf.MaxIdleConns)
  50. sqlDB.SetMaxOpenConns(conf.MaxOpenConns)
  51. }
  52. global.MYSQL = mysqlMap
  53. if mysqlConf.Binlog.IsListen {
  54. go binlog.ListenMysql()
  55. }
  56. fmt.Println("mysql init end")
  57. }