Redis Caching in 4 minutes
Tags: redis, caching, node, beginners
Published: 2023-05-27 12:40:30

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jgt3ckmc7k00qmvow6j.png)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fsoibn82nkqe4j9agnet.png)

**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
```
In terminal type below command to install `required npm packages` :

```
npm i redis express nodemon
```

Start your local machine redis-server in terminal :

```
redis-server
```
It may look like this :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7msi9dwxr4tca2li569t.png)

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');
})
```

Now make the following changes in your `package.json` :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/co1q9p1zcl26l5dkrlh5.png)


Now open another terminal to start this server type :

```
npm run devStart
```
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());
...
```
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`);
})
```

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`)
    }
})
```

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');
})
```
Testing our redis-datastore using Postman :
1.POST Request :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iaazp2pykz93gayizv2t.png)

2.GET Request :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/afefn0bf1y6dsubmncnt.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h1x8eoo19qdglov8n22j.png)

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.