trong
trong

Reputation: 133

What is correct way to close persistent connection?

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!

Upvotes: 0

Views: 195

Answers (1)

evanmcdonnal
evanmcdonnal

Reputation: 48114

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.

Upvotes: 1

Related Questions