I’m trying to make a robust reconnect mechanism for redis in Nest.js microservices.
How do I test reconnect:
I bootstrap microservice(as hybrid application in my case). With working Redis in docker compose.
After that I turn Redis off. Check my my microservice will work with that and after some time I turn Redis on.
Current behaviour:
Microservice make retry attempts only provided times. After that my microservice will not try to connect to the Redis, even if Redis is available.
What I want to implement:
I want to make retries till the moment when microservice connect to the Redis. That’s why I try to use retryStrategy and reconnectOnError. But none of them will work in case of unavailable Redis service.
Dependencies:
"@nestjs/microservices": "^10.4.3",
"ioredis": "^5.4.1",
"@nestjs/core": "^10.3.2",
Here is code of Nest.js microservice.
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { RedisOptions, Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/filters';
import {
MICROSERVICE_APP_PORT,
REDIS_HOST,
REDIS_PORT,
} from './config';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.connectMicroservice<RedisOptions>({
transport: Transport.REDIS,
options: {
host: REDIS_HOST,
port: REDIS_PORT,
retryAttempts: 3,
retryDelay: 100,
connectionName: 'MY_MICROSERVICE',
keepAlive: 1000,
autoResubscribe: true,
retryStrategy: (times: number) => {
console.log('retryStrategy ');
const delay = Math.min(times * 100, 3000);
return delay;
},
reconnectOnError: (err) => {
console.log('reconnectOnError');
console.log('err ', err);
return true;
},
},
});
app.useLogger(new Logger());
app.useGlobalFilters(new HttpExceptionFilter());
await app.startAllMicroservices();
process.on('unhandledRejection', (reason) => {
console.error('🚀 ~ process.unhandledRejection ~ :', reason);
app.get(Logger).debug(reason);
});
process.on('uncaughtException', (err) => {
console.error('🚀 ~ process.uncaughtException ~ :', err);
app.get(Logger).debug(err);
});
app.listen(MICROSERVICE_APP_PORT);
}
bootstrap();
I also try to add username and password to the Redis in order to simulate Redis error. In this case I will have error data in reconnectOnError, but if I return true it will not make retry attempts more than provided value.
Tyler Durden is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.