Setting up the Redis Cache for the MEAN Stack Application

Posted By : RAJAT KATIYAR | 26-Dec-2016

Set up Redis Cache Mean Stack

1. Create the Redis instance at the AWS and get the endpoint url for it.

2. Now using the instance url and the port no i.e 6379, the instance can be connected with the application.

3. In my application, I have used the NPM packages namely, "ioredis" for redis,"mongoose-with-redis" for connecting the mongoose with redis,"mongoose" for the mongodb.

4. Now using the ioredis npm, create the redis client.

 

    var redis = require('ioredis');

    var mongoose = require('mongoose');

    var mongoose_redis = require('mongoose-with-redis');

 

5. Creating the redis client now,

    var redis_client = redis.createClient({host:'',port:'',pass:’’});

 

     redis_client.on('connect', function() {

          console.log('Connected to redis cache');

        });

        redis_client.on('error', function() {

          console.log('Some error in connecting the redis cache');

        });

 

6. Once the redis_client is created, it is required to create the object which acts as an interface between the db and the redis. So let’s create that object also,

    var cache_options = {

             cache: true,

             expires: 800, //seconds

             prefix: 'test_cache'

           }

    mongoose_redis(mongoose, redis_client, cache_options);

7. Now the redis cache has been connected with the application and the mongodb.

8. Whenever the results is fetched from the mongodb, just put the lean() function, the result will be first checked in the redis cache and if found will be fetched to the user, but if there is no key found in the cache then the result will be fetched from the mongodb and then stored in the redis cache.

Example mongo query:

domain.User.find({phone:918989898989}).lean().exec(function(err,res){});

So the lean() function will help the mongoose_redis object to come in action and do the required things.

 

About Author

Author Image
RAJAT KATIYAR

Rajat Katiyar is a very bright web app developer, he has good knowledge of JAVA, C/C++, C#.NET. Apart from this he has interest in theater and sports.

Request for Proposal

Name is required

Comment is required

Sending message..