All you need to know to start a Node + Redis app

What is Redis?

Redis is a key-value pair in-memory data storage structure that you can use not only as a database but also as a cache, message broker, and streaming engine. It supports various data structures such as strings, arrays, sets, hashes, bitmaps, hyperloglogs, geospatial indexes, and streams. As a developer, when you begin with Redis, you might start with strings. We will develop a demo app that uses Redis as a cache.

Why do we need Redis?

You might be wondering why we need Redis when we have numerous SQL and NoSQL Database solutions.

Well, You should not replace your entire Database with Redis as It is not designed to do so. You should use Redis on top of your existing database solutions.

But, Why!

As I mentioned before, there are different uses of Redis. For example for Web Applications, you can use Redis as a Database cache. This can dramatically improve the performance of web applications.

When a user requests data from an API or Database, it takes some milliseconds to fetch that data and send it to the user. If the data requested is stored in the Redis cache, it is possible to fetch the same data from the Redis cache instead of using the main database for subsequent requests. Consequently, the delivery of data is much faster to the users, thereby improving performance and user experience.

Installing Redis

Installation on Linux

You can install the Redis as below. This will add the Redis repository to the apt index, update it and install it on your Linux system.

curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg

echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list

sudo apt-get update
sudo apt-get install redis

After the installation, you can start the Redis server. You can also test it by connecting to the Redis CLI. On the terminal, run the following command.

redis-cli

This will prompt the default host and port. You can enter ping , the command, and it will return PONG

127.0.0.1:6379> ping
PONG

If you press, Ctrl + C, you will terminate the Redis CLI.

PurposeLinux command
check the status of the redis-serversudo systemctl status redis
stop the redis-serversudo systemctl stop redis
restart the redis-serversudo systemctl restart redis-server

Installation on macOS

First of all, you can check if Homebrew is installed

$ brew --version

Then, you can install Redis by running

brew install redis

In order to test your installation run the following command on the terminal

$ redis-server

if the installation is successful, Redis will run in the foreground with the startup screen with a logo. you can stop it with Ctrl + C

if you want to start the Redis server in the background when you log in to your system, you can run the following command in the terminal

brew services start redis

if you need to stop

brew services stop redis

Installaiton on Windows

Although there is no official support for windows, you can install windows subsystems for Linux ( WSL ) and then install Redis on WSL.

Redis installation on WSL is just as you installed it on Linux. Please check the above section on installation on Linux.

After the installation, start the Redis server as a service in the background by running the command below on the WSL terminal

sudo service redis-server start

Now, you can test the server, just as in any other Linux system, by connecting to Redis CLI and executing the ping command. (Please check the above section on installation on Linux)

you can also test by running redis-server command on WSL. This will starts Redis with a start-up screen logo in the foreground. If you need to stop it, press Ctrl + Z .

you can stop the Redis server running in the background with the following command

sudo service redis-server stop

Can Redis run Natively in Windows?

There are developer communities and companies working on running Redis natively on Windows. One such comapny is Memurai.

You can also check redis-windows, which is an unofficial version of Redis for Windows X64 systems.

Useful Redis commands for beginners

You can practice the Redis command on Redis CLI. For the most part, you will be working with strings when working with Redis as developers. However, Redis does offer other data types as well. Some of the most helpful commands for developers when working with strings are in the table below.

commandBasic usage( you can use lower case /upper case)
SETSET name john name is the key, and john is the value
GETGET nameuse the key( name ) to get the value
EXPIREEXPIRE name 1010 is in seconds
SETEXSETEX name 10 john{ name: john } expires in 10 seconds
you can test with ttl name on the terminal until it expires
KEYSKEYS *return all the keys on Redis. You should not use this in production. use this only for debugging your code.
FLUSHALLFLUSHALLclear all key-value pairs on Redis
DELDEL namedelete the key name and its associated value

In addition, You can check the usage of other commands in the official Redis documentation.

Let’s use Redis on the Node app

We will develop a demo application that uses Redis for caching. Assuming you have installed npm and the latest version of Node.js follow the steps below.

step 1

npm init

This will create a package.json file. Enter “index.js” as the entry point when creating package.json

Add “type”: “module”, as we will use ES 6 modules.

step 2

npm install express nodemon redis

step 3

Add “start”: “nodemon index.js”.

Step 4

Add the following code to index.js

import express from 'express';
import path from 'path';
import {fileURLToPath} from 'url';
import { createClient } from 'redis';


const app = express();
const port = 8080;

const client = createClient();
await client.connect();



const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/index.html'));
});


//read from Redis, if there is no posts, Data will be fetched from API.
//if there is data in Redis, this data will be returned
app.get('/getredis', ( req, res ) => {
       client.get('posts').then( data => { //getting Redis data
          if( data!= null ){          
            res.json( "Read from redis<br /><br />"+ data );
          }else{
                fetch('https://jsonplaceholder.typicode.com/posts/1')
                  .then((response) =>  response.json())
                  .then(
                    ( APIData ) => {                      
                      
                      client.set( 'posts' , JSON.stringify( APIData ));
                      res.json( "API Data<br /><br />"+
                        JSON.stringify(  APIData ) 
                        )
                }
              )
      
          }
        
        });
});


//clearing the redis cache
app.get("/clear", ( req, res ) =>{
       
  client.flushAll().then( ( reply ) => {    
  res.json( reply)

})
})



app.listen(port);
console.log('Server started at http://localhost:' + port);

Note:

Node Redis 4.x, does not support callbacks and it uses promises. Therefore you need to use .then() or async..await functions for Redis commands (ex: client.get() )

Therefore, the following code( from the official docs ) will not give the required output.

client.set('foo', 'bar', (err, reply) => {
    if (err) throw err;
    console.log(reply);

    client.get('foo', (err, reply) => {
        if (err) throw err;
        console.log(reply);
    });
});

you can replace app.get('/getredis',()) with the code below if you wish. It uses Async…await on in fetching Redis data

app.get('/getredis', async ( req, res ) => {
  const data = await client.get('posts');//getting Redis data
  
     if( data ){          
       res.json( "Read from redis<br /><br />"+ data );
     }else{
           fetch('https://jsonplaceholder.typicode.com/posts/1')
             .then( response =>  response.json())
             .then( APIData  => {                      
                 
                 client.set( 'posts' , JSON.stringify( APIData ));
                 res.json( "API Data<br /><br />"+
                   JSON.stringify(  APIData ) 
                   )
           }
         )
 
     }
   
  
});

Step 5

create Index.html, and add the following code

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Node + Express + Redis DEMO example</title>
  </head>
  <body>
    <h1>Node + Express + Redis DEMO </h1>   
    <button onClick="getData()">Get posts</button>
    <button onClick="clearRedis()">Clear Redis</button>
    <br /><br />
    <div id="display">Welcome</div>
  </body>
  <script>
   const clearRedis = () =>{
    fetch('/clear')
    .then((response) => response.json())
    .then((data) => document.getElementById('display').innerHTML= (data));
  }


  const getData = () =>{    
    fetch('/getredis')
    .then((response) => response.json())
    .then((data) => document.getElementById('display').innerHTML= data);
  }
  
  </script>
</html>

Testing the app

  1. click on the Get posts button. It will fetch data from the API
  2. Now refresh the browser
  3. Again click on Get posts the button. This time it will get data from the Redis cache
  4. If you want a clear Redis cache, click on Clear Redis
  5. Now, click on Get posts button. Since there are no records on the Redis cache, it will fetch data from API

In a large database or API with a large number of records, you will see a difference in time in fetching data. Reading data from API or Database is always slow compared to reading from the Redis database cache.

Resources

Download the Demo app

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *