我的資料庫連接及其吸氣劑如下:
func connectDB() (*gorm.DB, error) {
db, err := gorm.Open(postgres.Open(dbURL), &gorm.Config{})
if err != nil {
return nil, err
}
return db, nil
}
func GetDB() (*gorm.DB, error) {
if db == nil {
return connectDB()
} else {
return db, nil
}
}
我GetDB()在我的代碼中使用對資料庫進行操作。我的應用程式運行了大約 15 分鐘。如何確保連接db *gorm.DB在這段時間內不會超時?即使在 15 分鐘內沒有超時,如果由于網路錯誤等原因導致連接碰巧掉線,如何優雅地重新連接?
uj5u.com熱心網友回復:
GORM 使用database/sql來維護連接池。連接池可以處理連接超時和錯誤。連接池可以配置如下
sqlDB, err := db.DB()
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
sqlDB.SetMaxIdleConns(10)
// SetMaxOpenConns sets the maximum number of open connections to the database.
sqlDB.SetMaxOpenConns(100)
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
sqlDB.SetConnMaxLifetime(time.Hour)
uj5u.com熱心網友回復:
我建議你使用通用資料庫介面 *sql.DB ping() 函式https://gorm.io/docs/generic_interface.html
Ping 驗證與資料庫的連接是否仍然存在,必要時建立連接。
因此,每當您對資料庫發出新請求時(或僅針對您知道將在很長一段時間后執行的請求),您都可以先 ping 資料庫并確保它仍然處于活動狀態(在其他情況下,ping 會重新連接到db 自動),然后執行您的請求。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516136.html
