Redis is an open-source in-memory data store used for handling various data structures efficiently. It is widely used in modern applications for fast data access.
- Can be used as a database, cache, and message broker.
- Supports multiple data structures like strings, hashes, sets, and streams.
- Improves Node.js application performance by reducing cache size and enabling fast integration.
Prerequisites
Before starting with our application, make sure the following installation is in your system:
- An IDE of your choice.
- Redis is installed in your system. Check the version that you are using the following command:
redis cli --version- Node.js and NPM are installed and configured in your system.
- Basic knowledge of Node.js and Redis.
Implementing Redis Module
Step 1: Initialize the Application
First, initialize the project by creating a package.json file:
npm initStep 2: Install Redis Module
Install the Redis package using NPM:
npm install redis --saveStep 3: Create Redis Client
Create a file named app.js and add the following code:
const redis = require("redis");
const client = redis.createClient();
client.on("connect", () => {
console.log("Connection Successful!!");
});
client.on("error", (err) => {
console.log("Redis Error:", err);
});
client.connect();
- Here, the Redis module is imported and a Redis client is created.
- The connect event confirms a successful connection, while the error event handles connection errors.
- The client.connect() method establishes the connection (required in Redis v4).
Step 4: Run the Application
Run the application using:
node app.jsOutput:
Connection Successful!!Storing a String in Redis
To store a string in Redis, write the following code in the app.js file:Â
const redis = require("redis");
const client = redis.createClient();
client.on("connect", () => {
console.log("Connection Successful!!");
});
client.on("error", (err) => {
console.log("Redis Error:", err);
});
(async () => {
await client.connect();
try {
const result = await client.set("Intern", "gfg");
console.log(result);
} catch (err) {
console.log(err);
}
})();
- The set() method stores data in key-value format.
- Here, Intern is the key and gfg is the value.
- In Redis v4, set() returns a promise and logs OK on successful storage.
Output:
Connection Successful!!
OK
Retrieving a String Value
To get the value of the key stored in the Redis database, we will use the get function as shown below:
const redis = require("redis");
const client = redis.createClient();
client.on("connect", () => {
console.log("Connection Successful!!");
});
client.on("error", (err) => {
console.log("Redis Error:", err);
});
(async () => {
await client.connect();
try {
// Set value
const result = await client.set("Intern", "gfg");
console.log(result);
// Get value
const value = await client.get("Intern");
console.log(value);
} catch (err) {
console.log(err);
}
})();
The get() method retrieves the value associated with the specified key and prints it to the console.
Output:
Connection Successful!!
OK
gfg
Storing Objects in Redis (Hash)
To store objects in Redis database, write the following code:Â
const redis = require("redis");
const client = redis.createClient();
client.on("connect", () => {
console.log("Connection Successful!!");
});
client.on("error", (err) => {
console.log("Redis Error:", err);
});
(async () => {
await client.connect();
try {
// Store a string
const result = await client.set("Intern", "gfg");
console.log(result);
// Get the string value
const value = await client.get("Intern");
console.log(value);
// Store an object as a hash
await client.hSet("Interns", {
pos: "Tech Writer",
Org: "GFG"
});
} catch (err) {
console.log(err);
}
})();
- Redis hashes store objects as field–value pairs.
- Here, Interns is the hash key storing position and organization details.
- Now, the key will be Interns and its value will be { pos: "Tech Writer", Org: "GFG" }.
Retrieving Object Values from Redis
To get the value from the Redis database, write the following code:
const redis = require("redis");
const client = redis.createClient();
client.on("connect", () => {
console.log("Connection Successful!!");
});
client.on("error", (err) => {
console.log("Redis Error:", err);
});
(async () => {
await client.connect();
try {
// Store a string
const result = await client.set("Intern", "gfg");
console.log(result);
// Get the string value
const value = await client.get("Intern");
console.log(value);
// Store an object as a hash
await client.hSet("Interns", {
pos: "Tech Writer",
Org: "GFG"
});
// Get all values from the hash
const data = await client.hGetAll("Interns");
console.log(data);
} catch (err) {
console.log(err);
}
})();
The hGetAll() method retrieves all field-value pairs from the hash and displays them as an object.
Output:
Connection Successful!!
OK
gfg
{ pos: 'Tech Writer', Org: 'GFG' }