gorm.Open() 是否在每次调用时都创建一个新的连接池?

Does gorm.Open() create a new connection pool every time it's called?

我正在编写一段代码,它从几个不同的地方调用数据库。在这段代码中,我一直在使用 GORM 库,并在每次需要与数据库交互时调用 gorm.Open()

我想知道的是,当我调用它时,幕后发生了什么?是每次调用时都会创建一个新的连接池,还是每次调用 gorm.Open() 共享同一个连接池?

TLDR: 是的,尝试重新使用 returned DB 对象。

gorm.Open 执行以下操作:(或多或少):

  1. 查找给定方言的驱动程序
  2. 调用 sql.Open 到 return 一个 DB 对象
  3. 调用DB.Ping()强制它与数据库对话

这意味着为每个 gorm.Open 创建一个 sql.DB 对象。根据 doc,这意味着每个数据库对象一个连接池。

这意味着 sql.Open 的建议适用于 gorm.Open:

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

是的,还要注意在 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)

*gorm.DB 实例 returns 底层 *sql.DB 实例上调用 DB() 函数。