Redis: Data Caching
Tags: redis, javascript, node, database
Published: 2022-06-02 22:10:48

As developers we want to make our data queries from the server to the database seamless, inexpensive and fast. 
While there are a number of approaches to speed up this process, including data indexing, caching, clustering, and so on, let's focus on _caching_.
These procedures assist in avoiding a **full body scan**. 

> We are going to use Redis for data caching. Redis is a key-value in-memory data store that is used as a database, cache, streaming engine, and message broker by millions of developers. Get source code [here](https://github.com/drsimplegraffiti/Data-cachcing-Redis-NodeJs)

---

### 🎯Prerequisites
- Basic knowledge of Node.js
- Nodejs installed on your computer.
- [Download redis for windows](https://github.com/microsoftarchive/redis/releases)

---

After downloading and installing, let's run health-check to see if `redis` was properly installed. Run the command <kbd>redis-server</kbd>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3cpktttogl8cl1g6v7py.PNG)

Redis also provides a command line utility that can be used to send commands to Redis. This program is called redis-cli. Open another instance of your terminal to use the redis command line interface. Let's send the word `ping` to redis server, if you get `pong`, it means there is a communication established.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sciebdehtu99zih9y851.PNG)

---

##### Set and Get Keys
Redis stores data in the key:value pair.
##### Fig ❎
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o3og3bmnj7znjp19zbdm.PNG)
 
Here we set the key name to  `Zidane`.


Let's get the value from the key we just set using the `get` keyword.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9rklcqen2tuf8v2tfay.png)
 
---

#### Shutdown Redis
Let's say we want to shut down redis, we use the command 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9p7o2ysmdr1fva3ub4dx.png)

So when we want to get the values after shutting down we get this error log.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0nbu5qgg10a78itkacw.png)
  

---

##### Redis with Nodejs and Express Js
Initiate the project
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vppca3tqu15yz3jm3t7.png)

---

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

#### Set data using express
```javascript
const express = require('express');
const redis = require('redis');
const util = require('util');

const redisConnectionUrl = 'redis://127.0.0.1:6379';
const client = redis.createClient(redisConnectionUrl);

client.set = util.promisify(client.set);
client.get = util.promisify(client.get);

const app = express();

const port = process.env.PORT || 6767;
const host = process.env.PORT || '0.0.0.0';

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//Setting data to redis
app.post('/set', async (req, res) => {
  const { redis_key, redis_value } = req.body;
  const response = await client.set(redis_key, redis_value);
  return res.status(200).json(response);
});

app.listen(port, host, () => {
  console.log(`Server is running on port ${host}:${port}`);
});
```

I used the <mark>promisify()</mark> method to convert the callback based methods to the Promise based ones and this is the best method to convert callback based functions to Promise based functions.

Not let's test our endpoint using postman.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mvp65hqlzzm05cgmne1t.png)


We got `Ok` as the response just as we got in Fig ❎ under `Set and Get Keys` Section

---
 
##### Getting data to redis
Let's retrieve data set into redis
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1pnkhveubx5vxkuxticv.png)

---

#### Now let's use Redis to reduce event/load time
```javascript
...
app.get('/posts/:id', async (req, res) => {
  const { id } = req.params;

  //implement caching
  const cachedResponse = await client.get(`post:${id}`);
  if (cachedResponse) {
    return res.status(200).json(JSON.parse(cachedResponse));
  }

  const response = await axios.get(
    `https://jsonplaceholder.typicode.com/posts/${id}`
  );
  await client.set(`post:${id}`, JSON.stringify(response.data), 'EX', 5);
  return res.status(200).json(response.data);
});

...
```

```javascript
Here is the explanation for the code above:
1. We use axios to make the request to the API
2. We use the client.set method to cache the response
3. We use the client.get method to check if the response is cached
4. We use the client.set method to cache the response 
```

---

#### Now lets test using postman

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

The response time here is 766ms

---

If we resend the call, we get 9ms
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2oejxy0j9nwzdiqno57a.png)

According to this line of code <kbd>  await client.set(`post:${id}`, JSON.stringify(response.data), 'EX', 5)</kbd> we set the expiration to 5 seconds.

We experience a sluggish response if we refresh after 5 seconds. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5xxb4qa4m87qg4qid7kz.png)
 
---
  
### Conclusion
**_Recap_**
Caching Data is a process that stores multiple copies of data or files in a temporary storage location—or cache—so they can be accessed faster. 
I hope this post was helpful on how to use Redis for data caching.
Thanks for reading.

---

#### Resources
[Redis Docs](https://redis.io/docs/)
[redis npm](https://www.npmjs.com/package/redis)