DEV Community

Cover image for How to Implement Memcached in Nodejs Application
Pankaj Kumar
Pankaj Kumar

Posted on

How to Implement Memcached in Nodejs Application

Today, I am going to explain how we can install memcached in linux system and use it in our nodejs application.

As we know that performance matters for any mobile or web application and Caching is one of the easiest ways to increase any application performance. Lets try to understand the basics of memcached and how to use it in any nodejs application.

What is Memcached?

Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read. Memcached is free and open-source software, licensed under the Revised BSD licence. Memcached runs on Unix-like operating systems (at least LINUX and OS X) and on Microsoft windows.

We can store data to memcached server in key pair format. So whenever any request come from the app can be matched with memcached server without any query from mysql/Nosql server. This increases the performance of the application.

Now lets move to intigration part with nodejs application. Here I am using ubuntu machine, So with below command we can install memcahced in our ubuntu machine

sudo apt-get install memcached
Enter fullscreen mode Exit fullscreen mode

Once the above command run successfully, Check whether it is properly installed or not with below command.

telnet localhost 11211
Enter fullscreen mode Exit fullscreen mode

You will see something like below:

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Enter fullscreen mode Exit fullscreen mode

If you are gettting anything different from above then correct the issue within your system before proceeding ahead.

Now we will create package.json file like below

{
"name": "memcached",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "NA"
},
"author": "Suraj Roy",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4",
"memcached": "^2.2.2"
}
}
Enter fullscreen mode Exit fullscreen mode

now move to to project folder and run npm install

After installing the required package. Let's have a look inside index.js file.

var express = require("express");
var Memcached = require('memcached');
var app = express();

// Created object for memcached
var memcached = new Memcached();
/* code to connect with your memecahced server */
memcached.connect( 'localhost:11211', function( err, conn ){
if( err ) {
console.log( conn.server,'error while memcached connection!!');
}
});
// Object to store in the memcached.....
var user = {
'userId':'iuytredcvb12345sdfgh',
'userName':'testUser',
'emailId':'demo.jsonworld@gmail.com',
'phone' : 8287374553,
'availableFor' : '2 hours',
'createdOn':1543122402
}


// saving information to user key.
memcached.set('user', user, 10000, function (err) {
if(err) throw new err;
});


// method to get saved data....
memcached.get('user', function (err, data) {
console.log(data);
});

// method to delete the saved data
/*memcached.del('user', function (err) {
if(err) throw new err;
});*/



app.listen(3000,function(){
console.log("Server running on port 3000");
});
Enter fullscreen mode Exit fullscreen mode

In the above file, At the top we have included required package for nodejs app with memcached. Below that we have created object for memcached and then connection with memcached server. At the middle of the file we have created an object named user to store over memcached server. Now we have three methods first memcached.set(), for saving the user data to memcached.

Where memcached.set*(key, value, lifetime, callback)*
key: String the name of the key
value: Mixed Either a buffer, JSON, number or string that you want to store.
lifetime: Number, how long the data needs to be stored measured in seconds
callback: Function the callback

Second, memcached.get() to get the saved userdata from the memcached server. Third memcached.del(), to delete the saved data of user whenever required.

We can also get data saved at multiple keys, For that we will use below method:

memcached.getMulti(['key1', 'key2'], function (err, data) {
  console.log(data.key1);
  console.log(data.bkey2);
})
Enter fullscreen mode Exit fullscreen mode

For more detail visit official website : Click here to redirect
After running the app by typing the node index.js, we will get below output over terminal:

Server running on port 3000
{ userId: 'iuytredcvb12345sdfgh',
  userName: 'testUser',
  emailid: 'demo.jsonworld@gmail.com',
  phone: 8287374553,
  availableFor: '2 hours',
  createdOn: 1543122402 }
Enter fullscreen mode Exit fullscreen mode

That’s all for now. Thank you for reading and I hope this post will be very helpful for implementation of memcached in nodejs application.

This article was originally posted over JsonWorld
Thanks!

Top comments (0)