Redis: Data Caching

Redis: Data Caching

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


🎯Prerequisites


After downloading and installing, let's run health-check to see if redis was properly installed. Run the command redis-server Image description

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


Set and Get Keys

Redis stores data in the key:value pair.

Fig ❎

Image description

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


Shutdown Redis

Let's say we want to shut down redis, we use the command Image description

So when we want to get the values after shutting down we get this error log. Image description


Redis with Nodejs and Express Js

Initiate the project Image description


Install packages

Image description


Set data using express

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 promisify() 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

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


Now let's use Redis to reduce event/load time

...
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);
});

...
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

The response time here is 766ms


If we resend the call, we get 9ms Image description

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

We experience a sluggish response if we refresh after 5 seconds. Image description


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 redis npm