Using Redis To Cache Data In NodeJS And ExpressJS Server.
What is Cache?
- The Cache is Local Storage that is used to store frequently used data .
- Caching is the process of storing copies of files in a cache, or temporary storage location so that they can be accessed more quickly.
What is Redis?
- Redis Stands for Remote Dictionary Server.
- Redis is an open-source, in-memory key-value data store for use as a database, cache, message broker, and queue.
Install Redis Server:
Step 1: Download the latest Redis zip file from the official git hub location. For me it is Redis-2.4.5-win32-win64.zip.
Step 2: Extract the redis-2.4.5-win32-win64.zip file in your preferred location.
Step 3: It will come with two different folders, one is for 32bit, and another one is for 64bit based on your operating system.
Step 4: Goto 64bit there you can find the below files.
Step 4: Double click on the redis-server.exe file, there you can see the Redis-server startup and wait for connecting to clients like below.
Step 5: Now open the Redis-cli.exe file to Redis command-line interface.
As this acts as a Redis client, as soon as we open this cli, we can see the client-connected message in Redis server like below.
- Once Redis is installed then there are 2 ways to use Redis:-
- Installing Redis-CLI.
- Use Redis in the server application.
Step-1:- create Basic Express Server and installing packages.
- Once the Express server is created, now install the npm package named “ Axios ” to make a request to any third-party APIs. and import it.
npm install axios --save
- now create a route to handle the GET method on “ /starwar ” path.
- user parameters passed while accessing path to fetch data from a third party using Axios package.
Step:-2 Caching data using Redis.
- install Redis npm package.
npm i redis --save
- we have to first import redis npm package.
- Redis package gives us createClient() method which will accept Redis-server port no which is 6379 by default.
- In case any error arrives we can use client.on(“error”,()=>{}). middleware to log the error message.
- now while handling “/starwars ” route we have to cache the data received into Redis using client.setex() method.
Step:-3 Adding Middleware to check if data is present in Cache or not.
- Now we have to create middleware named checkCache ,which will have access to req,res and next.
- In side Middleware we can use client.get() method to check if required data is in cache or not.
- client.get() method will accept string as first parameter and call back function as second parameter.
- we can pass name of key which we need to search in Cache as first parameter.
- at last, we have to add this middleware in the route handler.