我正在编写一段代码,该代码从几个不同的地方调用数据库。在这段代码中,我一直在使用 GORM 库,并在gorm.Open()每次需要与数据库交互时调用。
我想知道的是当我调用它时引擎盖下发生了什么?每次调用时都会创建一个新的连接池,还是每次调用都gorm.Open()共享同一个连接池?
对于那些刚刚开始使用gorm的人,这里有一个更完整的示例。
db, err := gorm.Open(mysql.Open(url))
if err != nil {
// control error
}
sqlDB, err := db.DB()
if err != nil {
// control error
}
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)
Run Code Online (Sandbox Code Playgroud)
是的,还要注意连接池可以这样配置,在 GORM v1 和 v2 中:
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
db.DB().SetMaxIdleConns(10)
// SetMaxOpenConns sets the maximum number of open connections to the database.
db.DB().SetMaxOpenConns(100)
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
db.DB().SetConnMaxLifetime(time.Hour)
Run Code Online (Sandbox Code Playgroud)
DB()在*gorm.DB实例上调用函数返回底层*sql.DB实例。