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

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

问题描述

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

  func CreateUser(){
db,err:= sql.Open(postgres,user = postgres password = password dbname = api_dev sslmode = disable)
//在这里执行一些数据库操作
}

我想函数应该可以独立于db来工作,所以现在我有 sql.Open(...)在每个函数中。我不知道这是否是管理数据库连接的正确方法。



一旦应用程序启动并将db作为参数传递给相应的函数,我应该在某处将其打开吗?在每个函数中打开连接?

解决方案

每次打开数据库连接都是浪费资源,速度很慢。



相反,您应该创建一个当您的应用程序启动时(或首次请求时),并将其传递到需要的地方(例如作为函数参数或通过某些函数参数上下文),或者简单地把它变成一个全局变量,所以每个人都可以访问它。



$ b


$
p>返回的数据库对于多个goroutine的并发使用是安全的,并保持其自己的空闲连接池。因此,Open函数应该只调用一次。关闭数据库很少有必要。


您可以使用一个包 init() $ b $ $ $ $


$ b $ func init()函数初始化它: {
var err error
db,err = sql.Open(yourdriver,yourDs)
if err!= nil {
log.Fatal(Invalid DB config :,err)
}
}

sql.Open()可能不会创建到你的数据库的实际连接,它可能只是验证它的参数。要测试您是否可以真正连接到数据库,请使用 DB .Ping() ,例如:

  func init(){
var err error $ b $ 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)
}
}


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
}

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.

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.

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.

Quoting from the doc of sql.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.

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)
    }
}

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天全站免登陆