Reputation: 1639
I have a Node microservice listening to a queue and I persist some messages into a Redis (every 4-5 seconds), and I do not know which is the best option.
Should I keep an open connection to my Redis or it is better to open and close connections every time the database is used?
Upvotes: 5
Views: 4240
Reputation: 13953
As @SergioTulentsev explained, it is better to use a single connection.
If you are using ioredis
, you are covered because even if your client is disconencted, ioredis
will try to reconnect for you and also, it will have an in-memory command qeueu that it will fill up until the client is connected again and then, ioredis
will send all those command again.
https://github.com/luin/ioredis#offline-queue
When a command can't be processed by Redis (being sent before the ready event), by default, it's added to the offline queue and will be executed when it can be processed. You can disable this feature by setting the enableOfflineQueue option to false:
const redis = new Redis({ enableOfflineQueue: false });
Upvotes: 3