[英]When to release resources in a long running Go program?
I'm building a chat server using Go and Socket.io hence the server would be running indefinitely.我正在使用Go 和 Socket.io构建聊天服务器,因此服务器将无限期运行。 There are multiple resources which I need allocated upon the start of the program such as the database connection, redis connection, etc.
我需要在程序启动时分配多种资源,例如数据库连接、redis 连接等。
Now I'm wondering when all these connections should be released (closed)?现在我想知道什么时候应该释放(关闭)所有这些连接? Can I use
defer
in the main
function?我可以在
main
函数中使用defer
吗? Does that close them when main
reaches its end?当
main
到达终点时,这会关闭它们吗? Or should I just leave 'em open since the program will not exit on its own accord?或者我应该让它们保持打开状态,因为程序不会自行退出?
One thing I tend to do is this:我倾向于做的一件事是:
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
// Do stuff here
}
In run
you can then defer
as you are used to.在
run
您可以defer
习惯defer
。 However, in a long-running program like a server, IMO it's fine to just exit: The OS will clean up all resources taken up by the process automatically and whatever database or backend you have a connection to, has to be able to handle the process dying unexpectedly anyway .但是,在像服务器这样的长时间运行的程序中,IMO 可以直接退出:操作系统将自动清理进程占用的所有资源,并且您连接到的任何数据库或后端都必须能够处理无论如何,进程意外死亡。 This is called "crash-only software".
这称为“仅崩溃的软件”。
For tests, you should build your code in a way that it doesn't depend on global state - eg have a struct that has fields for the database connections etc. Make the business logic a method on that struct (or a function taking it).对于测试,您应该以不依赖于全局状态的方式构建代码 - 例如,有一个包含数据库连接字段的结构体等。使业务逻辑成为该结构体上的方法(或采用它的函数) . You can then in your
main
populate such a struct and call its methods.然后,您可以在
main
填充这样的结构并调用其方法。 And for testing, you can populate a struct, call its methods for whatever tests you want to do and then tear down the connections at the end of your test.对于测试,您可以填充一个结构,为您想要执行的任何测试调用其方法,然后在测试结束时拆除连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.