{"id":34034,"date":"2016-04-30T20:21:52","date_gmt":"2016-04-30T14:51:52","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=34034"},"modified":"2016-12-19T15:02:53","modified_gmt":"2016-12-19T09:32:53","slug":"caching-in-nodejs-using-redis","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/caching-in-nodejs-using-redis\/","title":{"rendered":"Caching in NodeJs using Redis"},"content":{"rendered":"<p>Whenever we talk <a title=\"Node.js consulting and development services\" href=\"http:\/\/www.tothenew.com\/mean-node-js-development-consulting\">about nodejs development<\/a>, the first thing that comes to our mind is managing concurrent requests in an efficient way. We can leverage our server performance and efficiency even more by providing a mechanism to cache it&#8217;s processed data(response) which seldomly changes. Such as products list, country codes, application configurations, etc.<\/p>\n<p>In this blog, we will be using the Redis(an in-memory data store) to achieve caching in a node server. To begin with it, we will need redis to be installed on to our machine (link : .<\/p>\n<p>After installing redis to your machine we can start the redis server.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-34035\" src=\"\/blog\/wp-ttn-blog\/uploads\/2016\/04\/redis.png\" alt=\"redis\" width=\"656\" height=\"546\" \/><\/p>\n<p>The default port of redis is 6379. For more details about redis you can refer to http:\/\/redis.io\/.<\/p>\n<p>Let us consider an example where we have to fetch list of products from a legacy application server, and the list of products seldomly changes. So we can easily cache these products list on our nodejs server. To do so, we need to require the redis module in our node application, which serves as a redis client to connect with the redis server.<\/p>\n<p>[js]<br \/>\nvar redis = require(&#8216;redis&#8217;);<br \/>\nvar client = redis.createClient(6379, &#8216;127.0.0.1&#8217;);<br \/>\n[\/js]<\/p>\n<p>Now we can use this client to store and fetch the data from the cache(redis).<\/p>\n<p>To store the value in redis:<\/p>\n<p>[js]<br \/>\nclient.set(&lt;key&gt;, JSON.stringify(&lt;value&gt;), function(error) { });<br \/>\n[\/js]<\/p>\n<p>And to fetch value from redis:<\/p>\n<p>[js]<br \/>\nclient.get(&lt;key&gt;, function(error, value) { });<br \/>\n[\/js]<\/p>\n<p>The below code demonstrates, how redis can be used with express framework(NodeJs)<\/p>\n<p>[js]<br \/>\nvar express = require(&#8216;express&#8217;);<br \/>\nvar app = express();<br \/>\nvar bodyParser = require(&#8216;body-parser&#8217;);<br \/>\nvar request = require(&#8216;request&#8217;);<\/p>\n<p>var redis = require(&#8216;redis&#8217;);<br \/>\nvar client = redis.createClient(6379, &#8216;127.0.0.1&#8217;);<\/p>\n<p>app.use(bodyParser.json());<br \/>\napp.use(bodyParser.urlencoded({<br \/>\n    extended: true<br \/>\n}));<\/p>\n<p>app.get(&#8216;\/products\/:id&#8217;, function (req, res) {<br \/>\n        client.get(req.params.id, function(error, product) {<br \/>\n            if (error) {throw error;}<br \/>\n            if (product) {<br \/>\n                res.json(JSON.parse(product));<br \/>\n            } else {<br \/>\n              request({uri: &#8216;&lt;some_other_domain&gt;\/products\/&#8217; + req.params.id}, function(error, response, body) \t\t\t\t\t\t\t  {<br \/>\n                    if (error) {throw error;return}<br \/>\n                    if (!error &amp;&amp; response.statusCode === 200) {<br \/>\n                        res.json(body);<br \/>\n                        client.set(req.params.id, JSON.stringify(body), function (error) {<br \/>\n                            if (error) {throw error;}<br \/>\n                        });<br \/>\n                    } else {<br \/>\n                        res.send(response.statusCode);<br \/>\n                    }<br \/>\n                });<br \/>\n            }<br \/>\n        });<br \/>\n    });<\/p>\n<p>var server = app.listen(3000, function () {<br \/>\n    console.log(&#8216;Server running at &#8216;);<br \/>\n});[\/js]<\/p>\n<p>The products API first try to check the data in the redis, before fetching it from \u201csome_other_domain\u201d. If the data is present in redis then, it will fetch it from the memory and respond back to the request. Else it will make a request to the \u201csome_other_domain\u201d and then store the response to redis before responding back to the request, so that it can be cached.<\/p>\n<p>If you want to set an expiration time for the cache, you can do so by using the \u2018setex\u2019 method of redis module.<\/p>\n<p>Syntax:<\/p>\n<p>[js]<br \/>\nclient.setex(&lt;key&gt;, &lt;expirationTimeInSeconds&gt;, JSON.stringify(&lt;value&gt;), function (error) { });<br \/>\n[\/js]<\/p>\n<p>Similarly, we can also cache database result sets in redis, to enhance the performance of the APIs. By specifying expiration we can also take the advantage of refreshing our server cache as per the need of our application.<\/p>\n<p>To demonstrate the API performance, I fetched 5000 records from a different server. It took around 19 seconds to respond without caching. And after caching the data on our node server, it just took around 110 millisecond to respond back.<\/p>\n<p>Without Caching the response from our server:<br \/>\n<img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-34036\" src=\"\/blog\/wp-ttn-blog\/uploads\/2016\/04\/without-cache.png\" alt=\"without cache\" width=\"1366\" height=\"716\" \/><\/p>\n<p>Server response, after caching the request on Redis:<br \/>\n<img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-34037\" src=\"\/blog\/wp-ttn-blog\/uploads\/2016\/04\/after-cache.png\" alt=\"after cache\" width=\"1366\" height=\"716\" \/><\/p>\n<p>This difference is self explanatory, to understand the power of caching with redis.<\/p>\n<p>Hope this will help. Happy coding.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Whenever we talk about nodejs development, the first thing that comes to our mind is managing concurrent requests in an efficient way. We can leverage our server performance and efficiency even more by providing a mechanism to cache it&#8217;s processed data(response) which seldomly changes. Such as products list, country codes, application configurations, etc. In this [&hellip;]<\/p>\n","protected":false},"author":99,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":4},"categories":[1185,1],"tags":[1072,3284,55,1177,2683,857],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/34034"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/99"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=34034"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/34034\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=34034"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=34034"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=34034"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}