什么时候应该在这个简单的Web应用程序中关闭数据库连接? [英] When should I close the database connection in this simple web app?

查看:101
本文介绍了什么时候应该在这个简单的Web应用程序中关闭数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用PostgreSQL的简单Go Web应用程序.我的main函数看起来像

I’m writing a simple Go web application that uses PostgreSQL. My main function looks like

var db *sql.DB

func main() {
    var err error
    db, err = sql.Open("postgres", "...")
    if err != nil {
        log.Fatalf("Couldn't connect to the database: %v", err)
    }

    http.HandleFunc("/whatever", whateverHandler)
    http.ListenAndServe("127.0.0.1:8080", nil)
}

似乎我应该在某个时刻在数据库连接上调用Close(),但是什么时候?该应用程序将永久保存(即直到我用^C杀死它).如果我将代码放在ListenAndServe调用之后无法运行,因为我的^C已杀死了整个应用程序.我的应用程序的结构应该不同吗?

It seems like I should be calling Close() on the database connection at some point, but when? This application serves forever (i.e. until I kill it with ^C). If I put code after the ListenAndServe call it doesn’t get run, because my ^C has killed the entire application. Should my application be structured differently?

推荐答案

在这种特殊情况下,我倾向于说您甚至不需要打扰:连接将在程序结束时关闭,因此您不会泄漏任何东西.

In this particular case, I tend to say you don't even need to bother: the connection will be closed when the program end, so you won't leak anything.

如果您确实需要正确关闭设备,则更简单的选择是使用优美服务器,然后defer资源关闭.

If you really need to close things properly, the simpler choice is to use a graceful server, and defer the resources closing.

或者,如果您的用例更复杂,请手动捕获信号并妥善关闭以自己的方式(例如使用关闭渠道).

Or, if your use case is more complicated, do it by hand by catching signals and gracefully shutting down your own way (using a closing channel for example).

这篇关于什么时候应该在这个简单的Web应用程序中关闭数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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