
- Redis is the open source in-memory data structure store used as caching in applications.
- In this demo:-
We will learn to install and use Redis in Windows platform
- Redis can be installed using npm install redis –save command. The following screenshot shows the terminal with Redis installation.
- The updated project structure for RedisDemo will look like following screenshot.
- We need to install a redis server but it does not support windows officially.The unofficial Redis for windows platform Redis-x64-3.0.500.msi.
https://github.com/MSOpenTech/redis/releases
- The 1st window screen for redis-server installation is looks like following screenshot:-
- The following windows asks for port name where server will run in the machine.The default port is 6379 for the redis server.
- The following screenshot asks for the memory size that redis server takes.The default value is 512 MB.
- The following screenshot shows the success message of redis installation.
- After successful installation in windows 8.1 we can now start the redis-server service by using redis-server –service-start command in command prompt.The following screenshot shows the command prompt with redis-server start command in execution.
- The redis-server process can be stopped using redis-server –service-stop command .The following screenshot shows the command prompt with redis-server stop command in execution.
- The demo.js file contains the following code to create a Redis client and save the studentScore array.Also it contains the code to retrieve the redis object using key.The following code shows the content of demo.js file:-
var redis = require("redis"),
client = redis.createClient(),
studentScores = [
{name: 'Sandeep', subject: 'Computer', score: 75, roll: 'roll2'},
{name: 'John', subject: 'Mathematics', score: 175, roll: 'roll3'},
{name: 'Kelly', subject: 'computer', score: 55, roll: 'roll4'},
{name: 'Smith', subject: 'Mathematics', score: 35, roll: 'roll1'}
];
//save the object as key-value pair
//roll will be key and value will be stringified of student object
studentScores.forEach(function(aStudent, i){
client.set(aStudent.roll, JSON.stringify(aStudent), redis.print);
});
//get the object for roll1 and parse it to JSON and display properties
client.get('roll1', function (err,result) {
var aStudent = JSON.parse(result)
console.log("Typeof: "+typeof aStudent);
console.log("Name: "+aStudent.name);
console.log("Subject: "+aStudent.subject);
client.quit();
});
client.on('error', function (err) {
console.log('error event - ', err);
});
- We can run the demo using node demo.js command.The following screenshot shows the terminal with output of the demo.
- The demo code can be downloaded from the following screenshot:-
https://github.com/saan1984/RedisDemo
