go-redis
go-redis copied to clipboard
Should we use defer close after new a redis client?
It is necessary to call defer client.Close()
after new a redis client?
It's always a good idea to explicitly close a resource (like a file handle or network connection) when you know you don't need it anymore, rather than letting the system close it for you when the process ends. That's why you'll see that pattern a lot in Go. In languages other than go, you'll see code that closes things like a Redis client in a handler that the program expects to be called when the program ends. In Go, it's common to use defer functionName()
because defer
gaurantees that the function called with it runs at the end of the current function.
So, given this, no it is not "neccessary" to call it that particular way. But, if you're setting up a client in your app's main
function, then yes, it's highly recommended.
@chenweiyj doesn't @mattwelke answered the question? In my opinion, it would be much easier to navigate through issues if resolved ones are closed.
I'd consider this solved. @chemidy If you still have questions, you shouldn't re-open this issue. Stack Overflow is a much better platform for asking specific questions related to programming. GitHub issues should be reserved for things you think the library maintainers need to be made aware of.
It's always a good idea to explicitly close a resource (like a file handle or network connection) when you know you don't need it anymore, rather than letting the system close it for you when the process ends. That's why you'll see that pattern a lot in Go. In languages other than go, you'll see code that closes things like a Redis client in a handler that the program expects to be called when the program ends. In Go, it's common to use
defer functionName()
becausedefer
gaurantees that the function called with it runs at the end of the current function.So, given this, no it is not "neccessary" to call it that particular way. But, if you're setting up a client in your app's
main
function, then yes, it's highly recommended.
how the redis-go close the client automatically?
So, given this, no it is not "neccessary" to call it that particular way. But, if you're setting up a client in your app's main function, then yes, it's highly recommended.
Should this be documented? I didn't find it very clear from the current docs ( https://pkg.go.dev/github.com/redis/go-redis/v9#Client.Close):
It is rare to Close a Client, as the Client is meant to be long-lived and shared between many goroutines.
Nor do I see it in any of the examples. Should that line in the docs be removed? Or maybe reworded?