Loading

Simple Cache With Redis and Node.js

Using Redis to Store Expiring Data with Node.js and Express

Barnabas Nomo | Tue, June 28th 2016


What is Redis?

Redis is a fast, open source, in-memory key-value data structure store that comes with a set of versatile in-memory data structures which enable the easy creation of varieties of custom applications.

In this example, we'll use axios to make get requests to https://quotes.rest/. Since, we'll not be allowed to make so many calls to the server on the free tier, we'll use redis to cache the data for a while. During that time when the data is cached, our server will serve the data from redis and not make any query to https://quotes.rest/.

First, create your project folder:

mkdir redis-qod && cd redis-qod

Init npm defaults

npm init -y

 Next, let's install the following modules in our projec directory

npm install --save express redis axios moment

Express is a web application framework for Node.js designed for building web applications and APIs.

Axios is a Promise based HTTP client for the browser and node.js.

Moment is a lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.

The code below is fairly commented to guide you through.

var http = require('http');
var express = require('express');
var axios = require('axios');
var redis = require('redis');
var moment = require('moment');

// Set the redis url to an empty string
// if the environment variable can't be found
var redisURI = process.env.REDIS_URL || '';

// Connect to redis server
var redis_cli = redis.createClient(redisURI, {no_ready_check: true});

// Error event handler
redis_cli.on('error', function (err) {
    console.error("Error " + err);
});

var app = express();

// Homepage
app.get('/', function(req, res, next){
    // Check for today's quote of the day from redis.
    // I formatted the key because the jsons response 
    // brouhg back from querying the quote of the day
    // has a field call date, which is formatted as "2015-03-30"
    redis_cli.get(moment(new Date()).format("YYYY-MM-DD"), function(err,result) {
        // if record exists with that reference,
        // return the data received.
        if(result){
            res.json(JSON.parse(result));
        } else {
            // Otherwise, get quote from the external website and
            // save it. Set an expiry however to 
            // clean the cache every 2 hours.  ( In case the day advances )
            axios.get('http://quotes.rest/qod.json').then(function (response) {
                var myQuote = response.data.contents.quotes[0];

                // Stringify JSON object since redis doesn't deal with JSON data types.
                redis_cli.setex(myQuote.date, 7200, JSON.stringify(myQuote));
                // Send result back;
                res.send(myQuote);
            }).catch(function (err) {
                // Handle error
                console.log(err.message);
            });
        }
    });
});


http.createServer(app).listen(8000);