[go: up one dir, main page]

DEV Community

Cover image for Redis Caching in 4 minutes
SimardeepSingh1450
SimardeepSingh1450

Posted on

Redis Caching in 4 minutes

What is caching and why even use it in the first place ?
Caching means storing remote-data locally on your system for faster re-access.

What do I mean by faster re-access ?
Suppose there is a large Database(DB) of posts, the user wants to access one post out of such a large DB. Each time the user wants to access a post it will take some-time since the system will search in sequential order in DB for the specified post.
Example - I want to see the data of post-7, then the data would be sequentially searched in the DB, hence taking time.

Image description

So how to reduce this request-response wait-time ?
Hence steps in caching, redis-caching can be used with node-express API to make fetching data faster. With redis-caching an in-memory data-store is created which inturn creates key-value pairs thus providing faster retreival of data.
Whenever we search for a post-data in DB, our API will then first check if the key is present in redis-datastore, if present then returns the data with less-time and quick-response, else we can cache(store) the not cached-data, creating new key-value pair in its data-store for quick data retreival on re-access of same data accessed earlier.

Redis Key-Value DataStore Demonstration :

Image description

NOTE - You can also find the below source-code at :
https://github.com/SimardeepSingh1450/redis-in-4-minutes

So lets start making our own redis-API :

First of all, you need to install redis on your machine :
Visit http://redis.io and setup redis-server.

Create a folder with : mkdir myRedisApi
Go inside the folder : cd myRedisApi and create index.js file.

In terminal type below command to create package.json file :

npm init -y
Enter fullscreen mode Exit fullscreen mode

In terminal type below command to install required npm packages :

npm i redis express nodemon
Enter fullscreen mode Exit fullscreen mode

Start your local machine redis-server in terminal :

redis-server
Enter fullscreen mode Exit fullscreen mode

It may look like this :

Image description

Now in your index.js put the below code to create a simple express API :

const express = require('express');

const app = express();
app.use(express.json());

app.listen(8080,()=> {
    console.log('Server is listening on port-8080');
})
Enter fullscreen mode Exit fullscreen mode

Now make the following changes in your package.json :

Image description

Now open another terminal to start this server type :

npm run devStart
Enter fullscreen mode Exit fullscreen mode

Now put the redis-setup code in this order in index.js :

const express = require('express');
const redis = require('redis');

//redis-setup-code
const redisUrl = "redis://127.0.0.1:6379"
const client = redis.createClient(redisUrl);
client.connect();
client.on('connect',(err)=>{
    console.log('Redis connected!')
})

const app = express();
app.use(express.json());
...
Enter fullscreen mode Exit fullscreen mode

Here redisUrl = redis://localhost:portNumber and redis.createClient(redisUrl) creates our client for connecting to
redis-server.

Paste the below code in index.js for performing operations:
1.Storing new {key,value} pairs in redis-datastore using POST request :

app.post('/setKeyValue',async(req,res)=>{
    const {key,value} = req.body;
    console.log(key,value);
    await client.set(key,JSON.stringify(value));
    console.log(`${key}:${value} has been set`)
    res.json(`${key}:${value} has been set`);
})
Enter fullscreen mode Exit fullscreen mode

2.Retrieving the stored {key,value} pairs from redis using the GET request :

app.get('/:key',async(req,res)=>{
    const key = req.params.key;
    let cachedData = await client.get(key);
    if(cachedData){
        res.json(JSON.parse(cachedData));
    }else{
        res.json(`The Key(${key}) has no matching value in redis`)
    }
})
Enter fullscreen mode Exit fullscreen mode

Your final index.js code should be like this :

const express = require('express');
const redis = require('redis');

//redis-setup-code
const redisUrl = "redis://127.0.0.1:6379"
const client = redis.createClient(redisUrl);
client.connect();
client.on('connect',(err)=>{
    console.log('Redis connected!')
})

const app = express();
app.use(express.json());

app.post('/setKeyValue',async(req,res)=>{
    const {key,value} = req.body;
    console.log(key,value);
    await client.set(key,JSON.stringify(value));
    console.log(`${key}:${value} has been set`)
    res.json(`${key}:${value} has been set`);
})

app.get('/:key',async(req,res)=>{
    const key = req.params.key;
    let cachedData = await client.get(key);
    if(cachedData){
        res.json(JSON.parse(cachedData));
    }else{
        res.json(`The Key(${key}) has no matching value in redis`)
    }
})

app.listen(8080,()=> {
    console.log('Server is listening on port-8080');
})
Enter fullscreen mode Exit fullscreen mode

Testing our redis-datastore using Postman :
1.POST Request :

Image description

2.GET Request :

Image description

You can clearly see that it took only 9ms for the response, thus fast retreival of the data.

Image description

You have now gained the knowledge to implement redis in any API, hence time for some homework :

Try making a redis API with a Database such as MongoDB, MySql, etc. and see the difference in data response-time with and without implementation of redis.

Top comments (0)