dao.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package dao
  2. import (
  3. "fmt"
  4. "os"
  5. "time"
  6. "gorm.io/gorm/logger"
  7. "gorm.io/gorm/schema"
  8. // "github.com/xormplus/xorm"
  9. // "github.com/xormplus/xorm"
  10. "gorm.io/driver/mysql"
  11. "gorm.io/gorm"
  12. // _ "github.com/jinzhu/gorm/dialects/mysql"
  13. // "github.com/jinzhu/gorm"
  14. "kpt.xdmy/apiserver/config"
  15. "kpt.xdmy/apiserver/routers/restful"
  16. "kpt.xdmy/pkg/log"
  17. "kpt.xdmy/pkg/setting"
  18. )
  19. var D *Dao
  20. type Dao struct {
  21. DB *gorm.DB
  22. }
  23. func New(conf *config.Config) *Dao {
  24. newLogger := logger.New(
  25. log.New(os.Stdout, "\r\n"), // io writer
  26. logger.Config{
  27. SlowThreshold: time.Second, // Slow SQL threshold
  28. LogLevel: logger.Error, // Log level
  29. IgnoreRecordNotFoundError: false, // Ignore ErrRecordNotFound error for logger
  30. Colorful: true, // Disable color
  31. // LogMode:
  32. })
  33. gc := &gorm.Config{
  34. NamingStrategy: schema.NamingStrategy{
  35. SingularTable: true,
  36. NoLowerCase: true,
  37. },
  38. Logger: newLogger,
  39. // Logger: logger.Default.LogMode(logger.Silent),
  40. }
  41. db, err := gorm.Open(mysql.Open(conf.DB.DSN), gc)
  42. tx := db.Session(&gorm.Session{Logger: newLogger})
  43. // db.LogMode(true)
  44. if err != nil {
  45. log.Error("model.Setup err: %v", err, conf.DB.DSN)
  46. }
  47. sqlDB, _ := db.DB()
  48. // SetMaxOpenConns 设置打开数据库连接的最大数量。
  49. sqlDB.SetMaxOpenConns(100)
  50. // SetMaxIdleConns 设置空闲连接池中连接的最大数量
  51. sqlDB.SetMaxIdleConns(10)
  52. // SetConnMaxLifetime 设置了连接可复用的最大时间。
  53. sqlDB.SetConnMaxLifetime(300 * time.Second)
  54. D = &Dao{
  55. DB: tx,
  56. }
  57. return D
  58. }
  59. func Setup() {
  60. dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
  61. setting.DatabaseSetting.User,
  62. setting.DatabaseSetting.Password,
  63. setting.DatabaseSetting.Host,
  64. setting.DatabaseSetting.Name)
  65. // restful 接口的 数据库初始化
  66. err := restful.SQLInit("mysql", dsn, 500, 50, setting.DatabaseSetting.ShowXormlog)
  67. if err != nil {
  68. log.Fatal("dao Setup ", err)
  69. fmt.Println("dbs 数据库初始化失败 ")
  70. }
  71. if err != nil {
  72. log.Fatal("dao Setup ", err)
  73. }
  74. }