Is this the correct way to reuse the redis client?
Asked Answered
C

1

7

I have created a redis client module named redisConnection.js. It's contents are as follows

var redis = require('redis').createClient();

exports.exposeConnection = function(){

 return redis;

}; 

Now whenever I want to get make use of redis I just require the module and call the exposeConnection method. I wanted to know if this is right way to reuse the connection. I am hoping that redis connection is being instantiated only once and not every time I call the module. If not is there a better way reuse it?

Clostridium answered 11/10, 2013 at 6:51 Comment(4)
Can't really say whether it's "right." But, Node does cache modules based on their file path. So, as long as you don't have multiple redisConnection.js files, only one connection should be created among all require()s.Debi
@JonathanLonowski Thanks. Module caching was what I was looking for. Could you add an answer?Clostridium
I know this is not the answer to your question but it could be one way to achieve that client accessible throughout the application by doing - var redis = require('redis'); GLOBAL._REDISCLIENT = redis.createClient(port, server);Senlac
@Senlac Thanks for pointing this out. I did not know you could create GLOBAL variables in node js.Clostridium
T
8

That's almost similar to what I would I do(and what I have done in my previous apps).

Although instead of exposing it through a function I would just do this:

module.exports = require('redis').createClient();

So then later I can just do redis = require('./local-redis') instead of redis = require('./local-redis').exposeConnection().

This is a very simple but reliable architecture.

Thimbleful answered 15/4, 2014 at 18:56 Comment(2)
Thank you for the answer :) I had almost given up on this question.Clostridium
Be careful with using a single connection if you're using transaction commands such as WATCH, EXEC , MULTI. If the single connection is used concurrently, your code will likely be incorrect. You will need separate connections for correctness.Childish

© 2022 - 2024 — McMap. All rights reserved.