Integrating Redis in Your Node Application

Posted on - Last Modified on

Redis is an in-memory data structure store that can be used as a traditional database or as an in-memory cache. Redis was developed in ANSI C and was written with the need for performance in mind. Redis has the possibility to store the data to disk, but if that feature is disabled, it’s a perfect fit for an in-memory cache which can be used for speeding up websites and Web applications. Redis also has clients for many programming languages, from D and Dart to PHP, C#, JavaScript and Node.

Installation

Since Redis was written in ANSI C, most POSIX operating systems handle it properly. We have a version for OSX, Linux, and BSDs. Microsoft also supports a ported version of Redis for Windows.

On a Linux System, Redis can be installed using the commands below. This downloads the latest stable build from Redis website, extracts the tar file, and compiles it.

$ wget http://download.redis.io/releases/redis-3.0.4.tar.gz
$ tar xzf redis-3.0.4.tar.gz
$ cd redis-3.0.4
$ make

On a Windows machine, the prebuilt version can be downloaded from the MSOpenTech GitHub page.

After installing Redis, a new CLI will be available. When starting redis-cli and typing in the CLIENT LIST command, it should list all the active clients for the Redis server.

What can I store in Redis?

Redis can store a wide variety of data structures, from strings to lists of strings, sets, hashes and bitmaps. The keys for the values can be anything starting from strings to byte values or contents of a jpeg file, because the keys inside Redis are byte safe.

Redis and Node

In order to use Redis from Node the redis npm package has to be installed:

$ npm install redis

The code below creates a client to the redis server and sets up an error handler so we know what errors occurred during the execution of the script. Then we define a key for storing a simple string, SIMPLE_VALUE_KEY. As a best practice, redis keys should be composed using a composition of model hierarchy and colons.

var redis = require('redis');
var client = redis.createClient();

client.on('error', function(message){
   console.error(message);
});

var SIMPLE_VALUE_KEY = 'myapp:entities:values:1';

client.set(SIMPLE_VALUE_KEY,'Value1');  
client.get(SIMPLE_VALUE_KEY, function(err, replies){
    if(err) {
        console.error(err);
    }
    console.log(replies);
});

client.quit();

Next we set the Value1 assigned to the SIMPLE_VALUE_KEY. After setting the value we try to get the value from redis using the get method of the redis client. The get method’s second parameter is a function which has two parameters: the first is the error object (of course if there were errors), while the second parameter is data read from redis for the given key.

If we want to store arrays in redis we need to use the rpush or lpush methods as seen below:

function storeArray(client) {
    var ARRAY_VALUE_KEY = 'myapp:entities:arrays:1';
    var myPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 31, 37];

    client.rpush.apply(client, [ARRAY_VALUE_KEY].concat(myPrimes));

    client.lrange(ARRAY_VALUE_KEY, 0, -1, function(err, result){
        if(err){
            console.error(err);
        }
        console.log(result);
    });
}

Similar to storing simple values, the concept needs to define a key. The next step is to create the array (myPrimes) which we want to store. The next line applies the rpush method of the client for each element of the myPrimes array. The lrange method can be used to load the array/list elements from redis to get the key as first parameter. The second and third parameter stands for the start and end index of the items from the list. In this case, 0 and -1 signifies that we want all the elements from the list.

We can use the del method if we want to clear out values assigned to a key. 

function clearValue(client, key) {
    client.del(key, function(err, result){
        if(err) {
            console.error(err);
        }
        if(result > 0) {
            console.log(key + ' deleted from Redis.');
        }
    });
}

The method shown above receives the key and a callback function. The result variable will contain the number of deleted items from redis.

Posted 24 September, 2015

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Next Article

JS Testing with Jasmine