Redis is an remote dictionary server, an open-source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker.
Caching is the process of storing data into a software or hardware component so that future requests for that data can be served faster.
sudo apt update
sudo apt install redis-server
sudo systemctl status redis
npm init
we will use the following npm package in this project:
Express - for routing.
Node fetch - To make http request.
Redis - as node.js redis client.
nodemon - to setup & restart the server
Now that you have redis installed, add the following code to the index.js file.
var express = require('express')
var fetch = require("node-fetch");
var redis = require('redis')
var app = express()
var client = redis.createClient(6859)
client.on('error', (err) => {
console.log("Error " + err)
});
// get the list of photos
app.get('/photos', (req, res) => {
var photosRedisKey = 'user:photos';
// Firstly fetch the data from Redis in case we have it cached in redis
return client.get(photosRedisKey, (err, photos) => {
// If that data exists in Redis
if (photos) {
return res.json({ source: 'cache', data: JSON.parse(photos) })
} else {
// Now Fetch data directly from remote server api
fetch('https://jsonplaceholder.typicode.com/photos')
.then(response => response.json())
.then(photos => {
// Now Save the API response in Redis store, api server data automatically expire in 3600 seconds
client.setex(photosRedisKey, 3600, JSON.stringify(photos))
// Send JSON response to client browser
return res.json({ source: 'api', data: photos })
})
.catch(error => {
// log error message
console.log(error)
return res.json(error.toString())
})
}
});
});
// Assign express port at 3000
app.listen(3000, () => {
console.log('Server listening on port: ', 3000)
});
Goto postman and hit URL http://localhost:3000/photos and see the response time:
First Request :
Second Request:
The first request took 41ms and the second request took 30ms.
Redis is a very powerful in-memory data-store tool that we can use in our applications to cache data for upcoming requests. It's very simple to save and get data without much overhead.