db.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package initialize
  2. import (
  3. "Cold_Api/conf"
  4. _ "github.com/go-sql-driver/mysql"
  5. "fmt"
  6. "log"
  7. "time"
  8. "gorm.io/gorm/logger"
  9. "github.com/beego/beego/v2/core/logs"
  10. beego "github.com/beego/beego/v2/server/web"
  11. "gorm.io/driver/mysql"
  12. "gorm.io/gorm"
  13. )
  14. var DB *gorm.DB
  15. var Err error
  16. // 重写gorm日志的Writer
  17. type Writer struct {
  18. }
  19. func (w Writer) Printf(format string, args ...interface{}) {
  20. // log.Infof(format, args...)
  21. logs.Notice(format, args...)
  22. }
  23. // 设置psql
  24. func init() {
  25. log.Println("连接数据库...")
  26. sqlloglevel, err := beego.AppConfig.Int("sqlloglevel")
  27. if err != nil {
  28. log.Fatalf("无法获取sqlloglevel: %v", err)
  29. }
  30. slow_threshold, err := beego.AppConfig.Int("slow_threshold")
  31. if err != nil {
  32. log.Fatalf("无法获取slow_threshold: %v", err)
  33. }
  34. dataSource := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
  35. conf.MysqlServer_Username,
  36. conf.MysqlServer_Password,
  37. conf.MysqlServer_UrlPort,
  38. conf.MysqlServer_Database,
  39. )
  40. //设置gorm日志规则
  41. newLogger := logger.New(
  42. // log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer 单独设置grom日志输出
  43. Writer{}, // beego日志info输出
  44. logger.Config{
  45. SlowThreshold: time.Duration(slow_threshold) * time.Millisecond, // Slow SQL threshold
  46. LogLevel: logger.LogLevel(sqlloglevel), // Log level
  47. IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
  48. Colorful: true, // Disable color
  49. },
  50. )
  51. DB, Err = gorm.Open(mysql.Open(dataSource), &gorm.Config{
  52. DisableForeignKeyConstraintWhenMigrating: true, // 禁用外键
  53. Logger: newLogger,
  54. DisableAutomaticPing: true,
  55. })
  56. if Err != nil {
  57. log.Fatalf("连接数据库失败: %v", Err)
  58. }
  59. SqlDB, err2 := DB.DB()
  60. if err2 != nil {
  61. log.Fatalf("连接数据库失败: %v", err2)
  62. }
  63. SqlDB.SetMaxIdleConns(conf.MysqlServer_MaxIdleConnections)
  64. SqlDB.SetMaxOpenConns(conf.MysqlServer_MaxOpenConnections)
  65. SqlDB.SetConnMaxLifetime(time.Hour)
  66. log.Println("连接数据库完成...")
  67. }