doudou8081 2016-11-14 10:53
浏览 194

如何处理Go应用中的Db连接打开/关闭?

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?

  • 写回答

1条回答 默认 最新

  • dongxi5505 2016-11-14 10:56
    关注

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

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了