mysql.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. package dao
  2. import (
  3. "database/sql"
  4. "embed"
  5. _ "embed"
  6. "fmt"
  7. "git.rtzhtech.cn/iss/public-lib/config"
  8. "github.com/astaxie/beego/logs"
  9. "gorm.io/driver/mysql"
  10. "gorm.io/gorm"
  11. "io/ioutil"
  12. "path"
  13. "runtime"
  14. "time"
  15. )
  16. func ConnectDb(conf *config.Config) (*gorm.DB, error) {
  17. dsn := fmt.Sprintf(`%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local`,
  18. conf.Username,
  19. conf.Password,
  20. conf.Server,
  21. conf.Port,
  22. conf.Database,
  23. )
  24. dbMysql, err := gorm.Open(mysql.New(mysql.Config{
  25. DSN: dsn, // DSN data source name
  26. DefaultStringSize: 256, // string 类型字段的默认长度
  27. DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
  28. DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
  29. DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
  30. SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
  31. }), &gorm.Config{})
  32. if err != nil {
  33. logs.Error("链接mysql异常 err:" + err.Error())
  34. }
  35. sqlDb, _ := dbMysql.DB()
  36. // 对于中小型 web 应用程序,我通常使用以下设置作为起点,然后根据负载测试结果和实际吞吐量级别进行优化。
  37. // SetMaxIdleConns: 设置空闲连接池中链接的最大数量,这个连接数应大于等于打开的最大连接,否则需要额外连接时会频繁进行打开关闭。
  38. // 最好与最大连接数保持相同,当大于最大连接数时,内部自动会减少到与最大连接数相同。
  39. sqlDb.SetMaxIdleConns(200)
  40. // SetMaxOpenConns: 设置打开数据库链接的最大数量
  41. sqlDb.SetMaxOpenConns(200)
  42. // SetConnMaxLifetime: 设置链接可复用的最大时间,以确保连接可以被驱动安全关闭。官方建议小于5分钟。
  43. sqlDb.SetConnMaxLifetime(5 * time.Minute)
  44. // SetConnMaxIdleTime: 设置闲置连接的最大存在时间, support>=go1.15
  45. sqlDb.SetConnMaxIdleTime(5 * time.Minute)
  46. if conf.Debug.Mysql {
  47. dbMysql = dbMysql.Debug()
  48. }
  49. return dbMysql, err
  50. }
  51. func CreatDatabase(conf *config.Config) {
  52. dsn := fmt.Sprintf(`%s:%s@tcp(%s:%s)/`,
  53. conf.Username,
  54. conf.Password,
  55. conf.Server,
  56. conf.Port,
  57. )
  58. sqldb, err := sql.Open("mysql", dsn)
  59. if err != nil {
  60. logs.Error(err)
  61. }
  62. err = sqldb.Ping()
  63. if err != nil {
  64. sqldb.Close()
  65. } else {
  66. fmt.Println("Database is ready......")
  67. }
  68. sql := "CREATE DATABASE IF NOT EXISTS iss;"
  69. _, err = sqldb.Exec(sql)
  70. if err != nil {
  71. fmt.Println("创建数据库失败" + err.Error())
  72. }
  73. }
  74. //go:embed sql/base.sql
  75. var f embed.FS
  76. func TableInfo(conf *config.Config) {
  77. CreatDatabase(conf)
  78. db := OpenDatabase(conf)
  79. sqlBytes, err := f.ReadFile("sql/base.sql")
  80. if err != nil {
  81. logs.Error(err)
  82. }
  83. _, err = db.Exec(string(sqlBytes))
  84. if err != nil {
  85. logs.Error(err)
  86. }
  87. //filepath.Walk(getUrl(),
  88. // func(path string, f os.FileInfo, err error) error {
  89. // if f == nil {
  90. // return err
  91. // }
  92. // if !f.IsDir() {
  93. //
  94. // }
  95. // return nil
  96. // })
  97. }
  98. func OpenDatabase(conf *config.Config) *sql.DB {
  99. dsn := fmt.Sprintf(`%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&multiStatements=true`,
  100. conf.Username,
  101. conf.Password,
  102. conf.Server,
  103. conf.Port,
  104. conf.Database,
  105. )
  106. sqldb, err := sql.Open("mysql", dsn)
  107. if err != nil {
  108. logs.Error(err)
  109. }
  110. err = sqldb.Ping()
  111. if err != nil {
  112. sqldb.Close()
  113. } else {
  114. fmt.Println("Database is ready......")
  115. }
  116. return sqldb
  117. }
  118. func ExecTable(db *sql.DB, path string) {
  119. sqlBytes, err := ioutil.ReadFile(path)
  120. if err != nil {
  121. logs.Error(err)
  122. }
  123. _, err = db.Exec(string(sqlBytes))
  124. if err != nil {
  125. logs.Error(err)
  126. }
  127. }
  128. func getUrl() string {
  129. _, file, _, _ := runtime.Caller(1)
  130. file = file
  131. pathNew := path.Dir(file)
  132. return pathNew + "/../deploy/sql"
  133. }