Description
Environment:
- Node.js Version: v16.15.1
- Redis Server Version: unknown
- Node Redis Version: [email protected]
- Platform: Ubuntu 20.04.3
try {
const client = createClient(
{
socket: {
// deal ENOENT and ECONNREFUSED
path: this.unixDomainSocketPath, reconnectStrategy: (retries) => {
return 10000;
}
}
}
);
client.on('error',
(err) => {
logger.error(`LoopingPut ${err}. Action:${action},ResPut:${resPut},TimeOut:${this.timeOut}`);
}
);
await client.connect();
await client.sendCommand([action, this.contentType, resPut])
} catch (e) {
logger.error(`Catch ${e}. action:${action},resPut:${resPut},timeOut:${this.timeOut}`);
}
First when I run the code above, when happened error ENOENT,ECONNREFUSED, reconnectStrategy takes effect.It reconnect every ten seconds .But when happened ECONNRESET, the reconnectStrategy not in effect. Errors all over the screen every second,It seems it reconnect every second.
Second I found ENOENT or ECONNREFUSED means connect failed,so it run to reconnectStrategy. ECONNRESET means connect success,but sendCommand error,so it won't go to reconnectStrategy . It seems that it is sendCommand which retry every second.
Then I solve the question , you could use the following code to solve the problem.The point is that you must run client.disconnect() in .catch to prevent sendCommand retrying all the time.
try {
const client = createClient(
{
socket: {
// deal ENOENT and ECONNREFUSED
path: this.unixDomainSocketPath, reconnectStrategy: (retries) => {
return 10000;
}
}
}
);
client.on('error',
(err) => {
logger.error(`LoopingPut ${err}. Action:${action},ResPut:${resPut},TimeOut:${this.timeOut}`);
}
);
await client.connect();
client.sendCommand([action, this.contentType, resPut])
.then(() => {client.disconnect().then().catch();}
)
// deal ECONNRESET you must client.disconnect() to prevent sendCommand retry all the time
.catch(() => { client.disconnect().then().catch();});
} catch (e) {
logger.error(`Catch ${e}. action:${action},resPut:${resPut},timeOut:${this.timeOut}`);
}
Finally To run the code above,you could resolve the problem of retrying all the time.But I want to retry in my controll,like retry every 10s,so I do this through the following code.
public async Put(action: string, resPut: string) {
try {
const client = createClient(
{
socket: {
// deal ENOENT and ECONNREFUSED
path: this.unixDomainSocketPath, reconnectStrategy: (retries) => {
return 10000;
}
}
}
);
client.on('error',
(err) => {
logger.error(`put error`);
}
);
await client.connect();
client.sendCommand([action, this.contentType, resPut])
.then((result) => {
client.disconnect().then().catch();
}
)
// deal ECONNRESET
.catch(() => {
client.disconnect().then().catch();
// my custom retry strategy
setTimeout(() => {
this.Put(action, resPut);
}, 10000);
});
} catch (e) {
logger.error(`xxx`);
}
}
}