Introduction to Redis and How to Use Caching in Node.js using Redis

What is Redis?

What is Cache?

What is caching?

Why do we Cache?

Prerequisites

Node.JS
Redis Server
Postman
Code Editor (VsCode)

Installing Redis

sudo apt update
sudo apt install redis-server
sudo systemctl status redis
Output● redis-server.service - Advanced key-value store
Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2018-06-27 18:48:52 UTC; 12s ago
Docs: http://redis.io/documentation,
man:redis-server(1)
Process: 2421 ExecStop=/bin/kill -s TERM $MAINPID (code=exited, status=0/SUCCESS)
Process: 2424 ExecStart=/usr/bin/redis-server /etc/redis/redis.conf (code=exited, status=0/SUCCESS)
Main PID: 2445 (redis-server)
Tasks: 4 (limit: 4704)
CGroup: /system.slice/redis-server.service
└─2445 /usr/bin/redis-server 127.0.0.1:6379
. . .

Redis CLI

redis-cli
127.0.0.1:6379>
127.0.0.1:6379> set test "It's working!"Output
OK
127.0.0.1:6379> get testOutput
"It's working!"
127.0.0.1:6379> set title1 1
127.0.0.1:6379> set title2 2
127.0.0.1:6379> keys *
Output
1) "title2"
2) "title1"
127.0.0.1:6379> set mykey hello ex 30

Getting started with Redis in Node.js

mkdir redis-cache && cd redis-cache
npm init -y
npm i express redis axios
Folder Structure
const express = require("express");const app = express();const port = 8080;app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
module.exports = app;
const express = require("express");const app = express();const port = 8080;const axios = require("axios");app.get("/jobs", async (req, res) => {
try {
const { search, type, title } = req.query;
const foundResults = await axios.get(
`https://jobs.github.com/positions.json?search=${search}&type=${type}&title=${title}`
);
return res.status(200).send({
error: false,
data: foundResults.data
});
} catch (error) {
console.log(error);
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
const express = require("express");
const axios = require("axios");
const redis = require("redis");
const app = express();const port = 8080;// make a connection to the local instance of redis
const client = redis.createClient(6379);
client.on("error", error => {
console.error(error);
});
app.get("/jobs", (req, res) => {
try {
const { search, type, title } = req.query;
// Check the redis store for the data first
client.get("jobs", async (err, jobs) => {
if (jobs) {
return res.status(200).send({
error: false,
message: `Jobs from the cache`,
data: JSON.parse(jobs)
});
} else {
// When the data is not found in the cache then we can make request to the server
const foundResults = await axios.get(
`https://jobs.github.com/positions.json?search=${search}&type=${type}&title=${title}`
);
// save the record in the cache for subsequent request
client.setex("jobs", 1440, JSON.stringify(foundResults.data));
// return the result to the client
return res.status(200).send({
error: false,
message: `Jobs from the server`,
data: foundResults.data
});
}
});
} catch (error) {
console.log(error);
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
module.exports = app;

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store