Friday, 5 July 2013

How to use Node.js with Redis (Comprehensive Node.js series)

Today, we will be learning how to use Node.js with Redis. If you don't already know, Redis is a NoSQL in-memory database. You can, however, also use it for persistent data storage, if you really want to.

Pre-requisite
You need to have Node.js already installed on your machine. If you don't, you can refer to my, Node.js installation tutorial

Redis Installation
Let us install Redis now. Just follow these steps on your Ubuntu/Linux terminal, and you will have Redis installed and running in no time.
cd ~
mkdir Redis
cd Redis
wget http://redis.googlecode.com/files/redis-2.6.14.tar.gz
tar -xvzf redis-2.6.14.tar.gz
cd redis-2.6.14
make
That completes the installation. Now let us just test it as follows,
cd src
./redis-server --version
You should get output like,
Redis server v=2.6.14 sha=00000000:0 malloc=jemalloc-3.2.0 bits=32
Starting Redis
Redis is a server, and hence needs to run in the background. Let us start it, and redirect its logs to a file in /tmp
nohup ./redis-server > /tmp/redis.log 2>&1 &
Redis module Installation
We will be using the Redis binding for Node.js available at mranney/node_redis now. Installation is very simple if we use npm. Now get out of the Redis installation directory, and go to your directory where you write Node.js scripts, and type in the following,
npm install redis
That completes the setup. Let us now start writing some code to use our new Redis server.

Storing values in Redis database with Node
Our node script will use a module called redis. Data fetches from Redis are asynchronous. So you need to pass a function that can process the fetched value, to every get command. Most of the commands available in Redis have identical equivalents in the redis module. Here is a sample program that stores a value, and then prints it back.
var redis = require('redis');

// All Redis commands are available in this client
var client = redis.createClient(); 
client.set("hello","world");
client.get("hello", function(error, value){
    console.log(value);
});
A simple visitor counter using Redis and Node
You must have heard of these counters. They just tell you how many times your page on a website has been viewed. In this simple implementation, all we really do is increment a variable every time a page is loaded. Let that page be /index. Here is the complete code for it. Let us call this script counter.js.
var http = require('http');
var urlparser = require('url');
var redis = require('redis');
var client = redis.createClient();

// This function will display the pages
function serve(request,response){
    response.writeHead(
        200,
        {'Content-Type': 'text/html'}
    );

    var parsed_url = urlparser.parse(request.url,true);
    if(parsed_url.pathname == '/index'){

       //Let us call our counter my_counter
       //Here we increment its value atomically
       client.incr('my_counter');

       client.get('my_counter', function(err, val){
           response.end("<html>This page was visited "+val+" times</html>");
       });
    }
}

var server = http.createServer(serve);
server.listen(12340);
That is all. You now have a functional counter. Just run your script as,
node counter.js
Then, visit http://127.0.0.1:12340/index on your browser. When you visit it for the first time, you will see a message like,
This page was visited 1 times
Refresh the page and you will see that the counter has increased. Remember, for now, this is an in-memory database. Snapshots of this database are taken regularly, but by default, we can't expect the persistence to be as good as expected. So the counter value might be lost when your Redis server shuts down abruptly. To counter this problem, you can use the appendonly mode of Redis. This is slower, but your data will be safer. To enable this mode do the following,
cd ~/Redis/redis-2.6.14
vi redis.conf
Now find the line that starts with appendonly. If you see a no after that, make it a yes. Save this file and restart your Redis server. Your data is now persistent. However, I would generally not recommend using Redis to persist your data. There are better NoSQL databases for that purpose, like MongoDB. Redis is supposed to be in-memory and fast.

That is all for now. Hope you enjoyed this lesson. As always, your comments and feedback are welcome.

No comments:

Post a Comment