[英]What is correct way to close persistent connection?
My case is: long running server with connection to Redis. 我的情况是:与Redis连接的服务器运行时间长。 This server wait for SIGTERM signal for terminating.
该服务器等待SIGTERM信号终止。 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. 我知道defer-确实很棒,但不是持久连接,因为我不想为每个操作都打开与Redis的连接。
Thanks! 谢谢!
You would still use defer
if you want to ensure some block of code executes before exit. 如果要确保在退出之前执行某些代码块,仍可以使用
defer
。 The difference is in it's scope. 不同之处在于它的范围。 The scope of your connection and defer statement should be the same.
连接和defer语句的范围应该相同。 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. 您说过“因为我不想为每个操作都打开与Redis的连接”,但这只会在您推迟执行单个IO操作的某些方法的范围内的延迟时才出现问题。 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.
我只想明确地说,您可以推迟应用程序顶层的连接关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.