登录
首页 >  Golang >  Go问答

处理 gorm 连接 postgres 数据库时的超时和丢失情况

来源:stackoverflow

时间:2024-03-09 15:00:27 285浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《处理 gorm 连接 postgres 数据库时的超时和丢失情况》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我的数据库连接及其吸气剂如下:

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分钟内没有超时,如果由于网络错误等原因导致连接断开,如何优雅地重连?


正确答案


我建议您使用通用数据库接口*sql.db ping()函数https://gorm.io/docs/generic_interface.html

ping 验证与数据库的连接是否仍然有效,并在必要时建立连接。

因此,每当您向数据库发出新请求(或者仅针对您知道将在很长一段时间后执行的请求)时,您可以先 ping 数据库并确保它仍然处于活动状态(在其他情况下 ping自动重新连接到数据库),然后执行您的请求。

gorm 使用 database/sql 来维护连接池。连接池可以处理连接超时和错误。 connection pool可以配置如下

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)

本篇关于《处理 gorm 连接 postgres 数据库时的超时和丢失情况》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>