Ioredis
What is Ioredis?
Ioredis is a Redis client for Node and io.js, that works with Node callbacks and Bluebird promises.
Installing Ioredis
We can install Ioredis through the npm package manager:
npm install ioredis
Basic usage
We will be going through the basic steps to build a program using Ioredis.
The first step is importing the ioredis library in our server.js file
const Redis = require('ioredis');
Then we need to create a new Redis' instance, connecting to our Redis server, we should pass the construtor our redis' server IP direction or port
const redis = new Redis(); new Redis(); // Connect to 127.0.0.1:6379 new Redis(6380); // 127.0.0.1:6380 new Redis(6379, '192.168.1.1'); // 192.168.1.1:6379 new Redis('/tmp/redis.sock'); new Redis({ port: 6379, // Redis port host: '127.0.0.1', // Redis host family: 4, // 4 (IPv4) or 6 (IPv6) password: 'auth', db: 0 });
- Once done that we can start using redis.
Basic operations
We will be going through the basic operations needed for our project.
Get
redis.get('key', callback(err, res));
This function is used to obtain the value associated to a determined key from Redis, it returns the value, or null if the key is not found.
Key
String associated to our desired value.
Callback(err, res)
Function called once the response is received, "res" contains the response and "err" the corresponding error code, if there is any.
Set
redis.set('key', 'value', [parameters])
This function is used to store a value associated to a determined key.
Key
String that will be associated to our value.
Value
Value stored in the Redis database.
Parameters
Additional parameters passed to the redis Database. We will be using the 'ex' parameter.
"EX" parameter
This parameter is used to set an Expiration time for the database's values.
redis.set('key', 'value, 'ex', time);
Time
Seconds before the stored information is automatically removed.