Node, Express - REST API Performance test With & without Redis cache

c4r4x35

Srinivas Kandukuri

Posted on October 30, 2019

Node, Express - REST API Performance test With & without Redis cache

As per the official Redis site

"Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker".

For more info please go through link Redis

Now we are building sample REST API, testing with and without Redis integration.

CODE BASE GITHUB LINK redisCache_nodejs_express_API

Files/Folder Structure.

Redis

We are using Some external data-source(API) for testing purpose.

Snippet


function cacheMid(req,res,next){
    var api = req.path;
    client.get(api, function(err, data){
        if (data != null) {
            console.log("from Cache");
            res.send(JSON.parse(data));
        } else {
            next();
        }
    })
}

function getAPI(req,res){
   axios.get('http://datasource.kapsarc.org/api/datasets/1.0/search/?rows=500')
    .then(function (response) {
        var api = req.path;
        var dataset = response.data;
        client.setex(api, 50, JSON.stringify(dataset));
        console.log("from API");
        res.send(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
}

// Router
app.get('/getAPI',cacheMid, getAPI);

Enter fullscreen mode Exit fullscreen mode

When we call /getAPI in postman then cacheMid middleware get called and check for mapped key, here it is 'req.path' is the key
if the there is any data with key in redis database then it will return data, otherwise it will got to else block & call the external API, get the json data, then we are setting into redis database.

Performance API TEST

localhost:4000/getAPI

image

💖 💪 🙅 🚩
c4r4x35
Srinivas Kandukuri

Posted on October 30, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related