英文:
What is correct way to close persistent connection?
问题
我的案例是:一个长时间运行的服务器与Redis连接。这个服务器等待SIGTERM信号来终止。在我的应用程序终止后,保证释放连接的正确方法是什么?
我知道defer - 真的很好,但对于持久连接来说不适用,因为我不想为每个操作都打开与Redis的连接。
谢谢!
英文:
My case is: long running server with connection to Redis. This server wait for SIGTERM signal for terminating. What is the right way to guarantee to release connection after terminating of my application?
I know about defer - is really great, but not for persistent connection, because I do not want to open connection to Redis for each operation.
Thanks!
答案1
得分: 1
如果你想确保某段代码在退出之前执行,你仍然可以使用defer
。区别在于它的作用域。你的连接和defer
语句的作用域应该是相同的。我不知道你的应用是什么,但是为了提供一个具体的例子,你需要在命令行应用的主函数中延迟关闭连接,而不是在读写方法中。
你说“因为我不想为每个操作都打开 Redis 连接”,但是如果你将关闭连接的延迟放在执行单个 IO 操作的方法的作用域中,这只会使defer
变得棘手。如果你将延迟放在包含所有操作的作用域上方(即所有操作发生的地方),那么它将按照你的意愿执行。
初始化连接
延迟关闭连接
执行进行数据库 IO 的代码
如果上述代码是异步的,则在此处阻塞
程序正在退出,我的延迟在此处被调用
编辑:正如评论中指出的,延迟语句的执行不是保证的。我只是想明确一点,你可以在应用程序的顶层延迟关闭连接。
英文:
You would still use defer
if you want to ensure some block of code executes before exit. The difference is in it's scope. The scope of your connection and defer statement should be the same. I have no idea what your app is but to provide a concrete example, you need to defer the connection close in the main of you command line app, not in the methods that read and write.
You said "because I do not want to open connection to Redis for each operation" but that only makes defer problematic if you defer the close in the scope of some method that does a single IO operation. If you instead do the defer in the scope above a single operation (where all operations occur) then it will do waht you want;
init connection
defer connectionClose
begin execution of code that does db IO
block here if above is async
program is exiting, my defer is called here
EDIT: As pointed out in the comments, the execution of deferred statements in not guaranteed. I just want to make it clear that you can defer the connection closing at the top level of application.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论