package dao import ( "fmt" "os" "time" "gorm.io/gorm/logger" "gorm.io/gorm/schema" // "github.com/xormplus/xorm" // "github.com/xormplus/xorm" "gorm.io/driver/mysql" "gorm.io/gorm" // _ "github.com/jinzhu/gorm/dialects/mysql" // "github.com/jinzhu/gorm" "kpt.xdmy/apiserver/config" "kpt.xdmy/apiserver/routers/restful" "kpt.xdmy/pkg/log" "kpt.xdmy/pkg/setting" ) var D *Dao type Dao struct { DB *gorm.DB } func New(conf *config.Config) *Dao { newLogger := logger.New( log.New(os.Stdout, "\r\n"), // io writer logger.Config{ SlowThreshold: time.Second, // Slow SQL threshold LogLevel: logger.Error, // Log level IgnoreRecordNotFoundError: false, // Ignore ErrRecordNotFound error for logger Colorful: true, // Disable color // LogMode: }) gc := &gorm.Config{ NamingStrategy: schema.NamingStrategy{ SingularTable: true, NoLowerCase: true, }, Logger: newLogger, // Logger: logger.Default.LogMode(logger.Silent), } db, err := gorm.Open(mysql.Open(conf.DB.DSN), gc) tx := db.Session(&gorm.Session{Logger: newLogger}) // db.LogMode(true) if err != nil { log.Error("model.Setup err: %v", err, conf.DB.DSN) } sqlDB, _ := db.DB() // SetMaxOpenConns 设置打开数据库连接的最大数量。 sqlDB.SetMaxOpenConns(100) // SetMaxIdleConns 设置空闲连接池中连接的最大数量 sqlDB.SetMaxIdleConns(10) // SetConnMaxLifetime 设置了连接可复用的最大时间。 sqlDB.SetConnMaxLifetime(300 * time.Second) D = &Dao{ DB: tx, } return D } func Setup() { dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", setting.DatabaseSetting.User, setting.DatabaseSetting.Password, setting.DatabaseSetting.Host, setting.DatabaseSetting.Name) // restful 接口的 数据库初始化 err := restful.SQLInit("mysql", dsn, 500, 50, setting.DatabaseSetting.ShowXormlog) if err != nil { log.Fatal("dao Setup ", err) fmt.Println("dbs 数据库初始化失败 ") } if err != nil { log.Fatal("dao Setup ", err) } }