如何在 Go 应用程序中处理打开/关闭 Db 连接? [英] How do I handle opening/closing Db connection in a Go app?

查看:40
本文介绍了如何在 Go 应用程序中处理打开/关闭 Db 连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Web API 应用程序中有一组函数.他们对 Postgres 数据库中的数据执行一些操作.

I have a set of functions in my web API app. They perform some operations on the data in the Postgres database.

func CreateUser () {
    db, err := sql.Open("postgres", "user=postgres password=password dbname=api_dev sslmode=disable")
    // Do some db operations here
}

我认为函数应该彼此独立地与 db 一起使用,所以现在我在每个函数中都有 sql.Open(...) .不知道是不是管理db连接的正确方法.

I suppose functions should work with db independently from each other, so now I have sql.Open(...) inside each function. I don't know if it's a correct way to manage db connection.

我是否应该在应用程序启动后在某处打开它并将 db 作为参数传递给相应的函数,而不是在每个函数中都打开连接?

Should I open it somewhere once the app starts and pass db as an argument to the corresponding functions instead of opening the connection in every function?

推荐答案

每次需要的时候都打开一个数据库连接,既浪费资源又慢.

Opening a db connection every time it's needed is a waste of resources and it's slow.

相反,您应该创建一个 sql.DB 一次,当您的应用程序启动时(或在第一次需要时),将它传递到需要的地方(例如作为函数参数或通过某些上下文),或者简单地将其设为全局变量,以便每个人都可以访问它.从多个 goroutine 调用是安全的.

Instead, you should create an sql.DB once, when your application starts (or on first demand), and either pass it where it is needed (e.g. as a function parameter or via some context), or simply make it a global variable and so everyone can access it. It's safe to call from multiple goroutines.

引用自 sql.Open() 的文档一个>:

Quoting from the doc of sql.Open():

返回的数据库对于多个 goroutine 并发使用是安全的,并维护自己的空闲连接池.因此,应该只调用一次 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.

您可以使用包 init() 函数对其进行初始化:

You may use a package init() function to initialize it:

var db *sql.DB

func init() {
    var err error
    db, err = sql.Open("yourdriver", "yourDs")
    if err != nil {
        log.Fatal("Invalid DB config:", err)
    }
}

这里要注意的一件事是 sql.Open() 可能不会创建到您的数据库的实际连接,它可能只是验证其参数.要测试您是否可以实际连接到数据库,请使用 DB.Ping(),例如:

One thing to note here is that sql.Open() may not create an actual connection to your DB, it may just validate its arguments. To test if you can actually connect to the db, use DB.Ping(), e.g.:

func init() {
    var err error
    db, err = sql.Open("yourdriver", "yourDs")
    if err != nil {
        log.Fatal("Invalid DB config:", err)
    }
    if err = db.Ping(); err != nil {
        log.Fatal("DB unreachable:", err)
    }
}

这篇关于如何在 Go 应用程序中处理打开/关闭 Db 连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆