'Reusing Redis Connection: Socket Closed Unexpectedly - node-redis
First, let me tell you how I'm using Redis connection in my NodeJS application:
- I'm re-using one connection throughout the app using a singleton class.
class RDB {
static async getClient() {
if (this.client) {
return this.client
}
let startTime = Date.now();
this.client = createClient({
url: config.redis.uri
});
await this.client.connect();
return this.client;
}
}
For some reason - that I don't know - time to time my application crashes giving an error without any reason - this happens about once or twice a week:
Error: Socket closed unexpectedly
Now, my questions:
- Is using Redis connections like this alright? Is there something wrong with my approach?
- Why does this happen? Why is my socket closing unexpectedly?
- Is there a way to catch this error (using my approach) or any other good practice for implementing Redis connections?
Solution 1:[1]
You should declare a private static member 'client' of the RDB class, like this:
private static client;
In a static method, you can't reference instance of 'this', you need to reference the static class member like this:
RDB.client
And it would be better to check, whether the client's connection is open, rather than simply checking if the client exists (considering you are using the 'redis' npm library). Like this:
if (RDB.client && RDB.client.isOpen)
After the changes, your code should look like this:
class RDB {
private static client;
static async getClient() {
if (RDB.client && RDB.client.isOpen) {
return RDB.client;
}
RDB.client = createClient({
url: config.redis.uri
});
await RDB.client.connect();
return RDB.client;
}
}
Note: the connect() method and isOpen property only exist in redis version ^4.0.0.
Also, I don't understand what is the purpose of startTime variable, but you probably use it in your real code, just not in this snippet. Please let me know if this helped!
Solution 2:[2]
I had similar issue of socket close unexpectedly. The issue started while I upgraded node-redis from 3.x to 4.x. The issue was gone after I upgraded my redis-server from 5.x to 6.x.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jack Lin |
