Redis use as Caching Server with Nodejs
Posted By : Md Imroz Alam | 10-Jan-2017
configure redis with nodejs
var redis = require('redis');
var port = 6379;
var host = "127.0.0.1";
global.redisClient = null;
redisClient = redis.createClient(port, host);
redisClient.on('connect', function(err, reply) {
if (err) {
Logger.info("Error with connection with redis");
} else {
Logger.info("connected with redis");
}
});
set redis key
var data={ tranHash:tx_result,confirm:0 };
redisClient.set(requestid,JSON.stringify(data), function(err,object){
if(err){ console.log("adding set Error"); }
else{ console.log("Added succesfully set"); }
});
get redis key
redisClient.get(requestid, function(err, object) {
if(err){ console.log("Getting Set Error"); }
else{ console.log("----Retrieving SET--"); object=JSON.parse(object); console.log(object);
});
retrive all keys of redis
redisClient.multi()
.keys('*', function (err, replies) {
console.log("MULTI got " + replies.length + " replies");
replies.forEach(function (reply, index) {
console.log("Reply " + index + ": " + reply.toString());
});
}).exec(function (err, replies) {});
checking for redis key exist or not, save it if key is not stored otherwise access data by redis key(requestid)
var requestid = req.params.requestid;
redisClient.get(requestid, (err, object)=> {
if (err) {
console.log("Getting Set Error");
} else {
console.log("----Retrieving SET--");
object = JSON.parse(object);
console.log(object, typeof object);
if(object.confirm>=2){
resData.totalConfirmations = object.confirm;
callback(null,resData);
}else {
this.checkConfirmation(object.tranHash,(err,confirm) =>{
if(err){
callback(err,err);
}else {
var data={ tranHash:object.tranHash,confirm:confirm.totalConfirmations };
redisClient.set(requestid,JSON.stringify(data), (err,object) => {
if(err){ console.log("adding set Error"); }
else{ console.log("Added succesfully set"); console.log(object);
callback(null,confirm);
}
});
}
}); }
console.log("---End Retriving SET");
}
});
I hope this will be helpful
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Md Imroz Alam
Md. Imroz Alam is a bright Web App Developer, he has good knowledge of Java, J2SE, Jsp, Servlet, jdbc. His hobbies are watching movie, playing carom.