Welcome back to our Redis and Express tutorial series! In the previous sections, we set up Redis on our local machine and established the foundations of our Express.js application. Now, let's dive into the exciting part – adding and retrieving data using Redis.
Adding Data to Redis:
To add data to Redis, we'll create a new endpoint that accepts a POST request. Here's how you can do it:
// index.js
// index.js
const express = require("express");
const redis = require("redis");
const app = express();
const port = 8080;
const client = redis.createClient({
host: "127.0.0.1",
port: 6379,
});
client.on("error", (error) => {
if (error) {
console.error("ERROR***", error);
} else {
console.log("Redis connect.");
}
});
(async () => {
client.connect();
})();
app.use(express.json());
// Endpoint to add data to Redis
app.post("/", async (req, res) => {
const { key, value } = req.body;
// Set data in Redis
const response = await client.set(key, value);
// Respond with the Redis response
res.json(response);
});
app.listen(port, () => {
console.log(`Now listening on port ${port}`);
});
Now, you can use Postman or any other API testing tool to send a POST request to http://localhost:8080 with a JSON body containing a key and value. For example:
{
"key": "post",
"value": "This is a cool course"
}
Retrieving Data from Redis:
To retrieve data, we'll create another endpoint that accepts a GET request. Here's how you can implement it:
// index.js
const express = require("express");
const redis = require("redis");
const app = express();
const port = 8080;
const client = redis.createClient({
host: "127.0.0.1",
port: 6379,
});
client.on("error", (error) => {
if (error) {
console.error("ERROR***", error);
} else {
console.log("Redis connect.");
}
});
(async () => {
client.connect();
})();
app.use(express.json());
// Endpoint to add data to Redis
app.post("/", async (req, res) => {
const { key, value } = req.body;
// Set data in Redis
const response = await client.set(key, value);
// Respond with the Redis response
res.json(response);
});
app.get("/:key", async (req, res) => {
const { key } = req.params;
// Get data from Redis
const value = await client.get(key);
// Respond with the Redis value
res.json({ key, value });
});
app.listen(port, () => {
console.log(`Now listening on port ${port}`);
});
Now, you can send a GET request to http://localhost:880 with a JSON body containing the key you want to retrieve. For example:
{
"key": "post"
}
Practical Scenario: Interacting with Database and Redis:
In a real-world scenario, we want to check if the data exists in Redis before interacting with the database. If the data is in Redis, we return it; otherwise, we fetch it from the database, store it in Redis for future use, and then return it. Here's a sneak peek into our next section:
// index.js
const express = require("express");
const redis = require("redis");
const app = express();
const port = 8080;
const client = redis.createClient({
host: "127.0.0.1",
port: 6379,
});
client.on("error", (error) => {
if (error) {
console.error("ERROR***", error);
} else {
console.log("Redis connect.");
}
});
(async () => {
client.connect();
})();
app.use(express.json());
// Endpoint to add data to Redis
app.post("/", async (req, res) => {
const { key, value } = req.body;
// Set data in Redis
const response = await client.set(key, value);
// Respond with the Redis response
res.json(response);
});
app.get("/:key", async (req, res) => {
const { key } = req.params;
// Get data from Redis
const value = await client.get(key);
// Respond with the Redis value
res.json({ key, value });
});
app.get("/existing/:key", async (req, res) => {
const { key } = req.params;
// Check if data exists in Redis
const redisData = await client.get(key);
if (redisData) {
// If data is in Redis, return it
res.json({ key, redisData });
} else {
// If not, interact with the database and store the data in Redis
const databaseData = await fetchDataFromDatabase(key);
await client.set(key, databaseData);
// Return the data fetched from the database
res.json({ key, databaseData });
}
});
app.listen(port, () => {
console.log(`Now listening on port ${port}`);
});
Stay tuned for our next section, where we'll dive deeper into this practical scenario and demonstrate how to seamlessly integrate Redis caching with your database interactions. If you haven't already, make sure Redis is running, and your Express server is up and listening on port 880. Happy coding!
Top comments (0)