Develop a JavaScript application with Azure Cache for Redis

To create, move, or use a Redis database to Azure, you need an Azure Cache for Redis resource. Learn how to create the resource and use your database.

Create a resource for a Redis database

You can create a resource with:

Create an Azure Cache for Redis resource with Azure CLI

Use the following Azure CLI az redis create command in the Azure Cloud Shell to create a new Redis resource for your database.

az redis create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE-NAME \
    --location eastus \
    --sku Basic \
    --vm-size c0 \
    --enable-non-ssl-port

This command may take a couple of minutes to complete and creates a publicly available resource in the eastus region.

The response includes your server's configuration details including:

  • the version of Redis: redisVersion
  • ports: sslPort and port
{
  "accessKeys": null,
  "enableNonSslPort": true,
  "hostName": "YOUR-RESOURCE-NAME.redis.cache.windows.net",
  "id": "/subscriptions/YOUR-SUBSCRIPTION-ID-OR-NAME/resourceGroups/YOUR-RESOURCE-GROUP/providers/Microsoft.Cache/Redis/YOUR-RESOURCE-NAME",
  "instances": [
    {
      "isMaster": false,
      "nonSslPort": 13000,
      "shardId": null,
      "sslPort": 15000,
      "zone": null
    }
  ],
  "linkedServers": [],
  "location": "East US",
  "minimumTlsVersion": null,
  "name": "YOUR-RESOURCE-NAME",
  "port": 6379,
  "provisioningState": "Creating",
  "redisConfiguration": {
    "maxclients": "256",
    "maxfragmentationmemory-reserved": "12",
    "maxmemory-delta": "2",
    "maxmemory-reserved": "2"
  },
  "redisVersion": "4.0.14",
  "replicasPerMaster": null,
  "resourceGroup": "YOUR-RESOURCE-GROUP",
  "shardCount": null,
  "sku": {
    "capacity": 0,
    "family": "C",
    "name": "Basic"
  },
  "sslPort": 6380,
  "staticIp": null,
  "subnetId": null,
  "tags": {},
  "tenantSettings": {},
  "type": "Microsoft.Cache/Redis",
  "zones": null
}

Add firewall rule for your client IP address to Redis resource

Add firewall rules with az redis firewall-rules create command to define access to your cache from your client IP or your app's IP.

az redis firewall-rules create \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE-NAME \
    --rule-name AllowMyIP \
    --start-ip 123.123.123.123 \
    --end-ip 123.123.123.123

If you don't know your client IP address, use one of these methods:

  • Use the Azure portal to view and change your firewall rules, which include adding your detected client IP.
  • When you run your Node.js code, your receive an error about your firewall rules violation which includes your client IP address. Copy the IP address and use it to set your firewall rule.

Get the Redis keys with Azure CLI

Retrieve the Redis connection string for this instance with the az redis list-keys command:

az redis list-keys \
    --subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
    --resource-group YOUR-RESOURCE-GROUP \
    --name YOUR-RESOURCE-NAME

This returns the two keys:

{
    "primaryKey": "5Uey0GHWtCs9yr1FMUMcu1Sv17AJA2QMqPm9CyNKjAA=",
    "secondaryKey": "DEPr+3zWbL6d5XwxPajAriXKgoSeCqraN8SLSoiMWhM="
  }

Connect Azure Cache for Redis to your App service web app

Add connection information to your App service web app with az webapp config appsettings set command.

az webapp config appsettings set \
--subscription YOUR-SUBSCRIPTION-ID-OR-NAME \
--resource-group YOUR-RESOURCE-GROUP \
--name YOUR-APP-SERVICE-RESOURCE-NAME \
--settings "REDIS_URL=YOUR-REDIS-HOST-NAME" "REDIS_PORT=YOUR-REDIS-PORT" "REDIS_KEY=YOUR-REDIS-KEY"

Replace the following settings in the preceding code:

  • YOUR-SUBSCRIPTION-ID-OR-NAME
  • YOUR-RESOURCE-GROUP
  • YOUR-APP-SERVICE-RESOURCE-NAME
  • YOUR-REDIS-HOST-NAME
  • YOUR-REDIS-PORT
  • YOUR-REDIS-KEY

View and use your Redis database

While developing your Redis database with JavaScript, use the Redis console from the Azure portal to work with your database.

While developing your Redis database with JavaScript, use the Redis console from the Azure portal to work with your database.

This console provides Redis CLI functionality. Be aware some commands are not supported.

Once you have your resource created, import your data into your Redis resource from Azure Storage using the Azure portal.

Use native SDK packages to connect to Redis on Azure

The Redis database uses npm packages such as:

Install ioredis SDK

Use the following procedure to install the ioredis package and initialize your project.

  1. Make sure Node.js and npm are installed.

  2. Create a Node.js project in a new folder:

    mkdir DataDemo && \
        cd DataDemo && \
        npm init -y && \
        npm install ioredis \
        code .
    

    The command:

    • Creates a project folder named DataDemo
    • Changes the Bash terminal into that folder
    • Initializes the project, which creates the package.json file
    • Adds the ioredis npm SDK to the project
    • Opens the project in Visual Studio Code

Create JavaScript file to bulk insert data into Redis

  1. In Visual Studio Code, create a bulk_insert.js file.

  2. Download the MOCK_DATA.csv file and place it in the same directory as bulk_insert.js.

  3. Copy the following JavaScript code into bulk_insert.js:

    const Redis = require('ioredis');
    const fs = require('fs');
    const parse = require('csv-parser')
    const { finished } = require('stream/promises');
    
    const config = {
        "HOST": "YOUR-RESOURCE-NAME.redis.cache.windows.net",
        "KEY": "YOUR-RESOURCE-PASSWORD"
        ,
            "KEY_PREFIX": "demoExample:"
    }
    
    // Create Redis config object
    const configuration = {
        host: config.HOST,
        port: 6380,
        password: config.KEY,
        tls: {
            servername: config.HOST
        },
        database: 0,
        keyPrefix: config.KEY_PREFIX
    }
    var redis = new Redis(configuration);
    
    // insert each row into Redis
    async function insertData(readable) {
        for await (const row of readable) {
            await redis.set(`bar2:${row.id}`, JSON.stringify(row))
        }
    }
     
    /* 
    id,first_name,last_name,email,gender,ip_address
    1,Rodrigo,Lock,rlock0@eventbrite.com,Agender,73.93.61.37
    2,Nikos,Gutierrez,ngutierrez1@yahoo.com,Genderfluid,213.54.40.210
    3,Eada,Sotham,esotham2@yellowpages.com,Bigender,28.236.183.89
    4,Ana,Brazil,abrazil3@who.int,Polygender,142.30.140.225
    5,Roman,Rohmer,rrohmer4@admin.ch,Genderqueer,235.197.52.85
    6,Elyn,Sute,esute5@ftc.gov,Genderqueer,171.151.109.188
    7,Omero,Childers,ochilders6@stanford.edu,Bigender,133.21.192.66
    8,Stephana,Pipet,spipet7@parallels.com,Genderfluid,177.48.129.213
    9,Anthiathia,Ulster,aulster8@weebly.com,Genderfluid,175.1.59.106
    10,Yard,Pyson,ypyson9@jalbum.net,Non-binary,0.8.135.151
    */
    
    // read file, parse CSV, each row is a chunck
    const readable = fs
        .createReadStream('./MOCK_DATA.csv')
        .pipe(parse());
    
    // Pipe rows to insert function
    insertData(readable)
    .then(() => {
        console.log('succeeded');
        redis.disconnect();
    })
    .catch(console.error);
    
  4. Replace the following in the script with your Redis resource information:

    • YOUR-RESOURCE-NAME
    • YOUR-AZURE-REDIS-RESOURCE-KEY
  5. Run the script.

    node bulk_insert.js
    

Create JavaScript code to use Redis

  1. In Visual Studio Code, create a index.js file.

  2. Copy the following JavaScript code into index.js:

    const redis = require('ioredis');
    
    const config = {
        "HOST": "YOUR-RESOURCE-NAME.redis.cache.windows.net",
        "KEY": "YOUR-RESOURCE-PASSWORD",
        "TIMEOUT": 300,
        "KEY_PREFIX": "demoExample:"
    }
    
    // Create Redis config object
    const configuration = {
        host: config.HOST,
        port: 6380,
        password: config.KEY,
        timeout: config.TIMEOUT,
        tls: {
            servername: config.HOST
        },
        database: 0,
        keyPrefix: config.KEY_PREFIX
    }
    
    const connect = () => {
        return redis.createClient(configuration);
    }
    
    const set = async (client, key, expiresInSeconds=configuration.timeout, stringify=true, data) => {
        return await client.setex(key, expiresInSeconds, stringify? JSON.stringify(data): data);
    }
    
    const get = async (client, key, stringParse=true) => {
        const value = await client.get(key);
        return stringParse ? JSON.parse(value) : value;
    }
    
    const remove = async (client, key) => {
          return await client.del(key);
    }
    
    const disconnect = (client) => {
        client.disconnect();
    }
    
    const test = async () => {
        
        // connect
        const dbConnection = await connect();
        
        // set
        const setResult1 = await set(dbConnection, "r1", "1000000", false, "record 1");
        const setResult2 = await set(dbConnection, "r2", "1000000", false, "record 2");
        const setResult3 = await set(dbConnection, "r3", "1000000", false, "record 3");
    
        // get
        const val2 = await get(dbConnection, "r2", false);
        console.log(val2);
        
        // delete
        const remove2 = await remove(dbConnection, "r2");
        
        // get again = won't be there
        const val2Again = await get(dbConnection, "r2", false);
        console.log(val2Again);
        
        // done
        disconnect(dbConnection)
    }
    
    test()
    .then(() => console.log("done"))
    .catch(err => console.log(err))
    
  3. Replace the following in the script with your Redis resource information:

    • YOUR-RESOURCE-NAME
    • YOUR-RESOURCE-PASSWORD
  4. Run the script.

    node index.js
    

    The script inserts 3 keys then deletes the middle key. The console results are:

    record 2
    null
    done
    

Use Redis console in Azure portal to view data

In the Azure portal, view your resource's console with the command SCAN 0 COUNT 1000 MATCH *.

In the Azure portal, view your resource's console with the command `SCAN 0 COUNT 1000 MATCH *`.

Next steps