Quickstart: Use Azure Cache for Redis in Java

In this quickstart, you incorporate Azure Cache for Redis into a Java app using the Jedis Redis client to have access to a secure, dedicated cache that is accessible from any application within Azure.

Skip to the code on GitHub

If you want to skip straight to the code, see the Java quickstart on GitHub.

Prerequisites

Create an Azure Cache for Redis

  1. To create a cache, sign in to the Azure portal and select Create a resource.

    Create a resource is highlighted in the left navigation pane.

  2. On the New page, select Databases and then select Azure Cache for Redis.

    On New, Databases is highlighted, and Azure Cache for Redis is highlighted.

  3. On the New Redis Cache page, configure the settings for your new cache.

    Setting Choose a value Description
    Subscription Drop down and select your subscription. The subscription under which to create this new Azure Cache for Redis instance.
    Resource group Drop down and select a resource group, or select Create new and enter a new resource group name. Name for the resource group in which to create your cache and other resources. By putting all your app resources in one resource group, you can easily manage or delete them together.
    DNS name Enter a unique name. The cache name must be a string between 1 and 63 characters that contain only numbers, letters, or hyphens. The name must start and end with a number or letter, and can't contain consecutive hyphens. Your cache instance's host name will be <DNS name>.redis.cache.windows.net.
    Location Drop down and select a location. Select a region near other services that will use your cache.
    Cache type Drop down and select a tier. The tier determines the size, performance, and features that are available for the cache. For more information, see Azure Cache for Redis Overview.
  4. Select the Networking tab or select the Networking button at the bottom of the page.

  5. In the Networking tab, select your connectivity method.

  6. Select the Next: Advanced tab or select the Next: Advanced button on the bottom of the page.

  7. In the Advanced tab for a basic or standard cache instance, select the enable toggle if you want to enable a non-TLS port. You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

    Redis version 4 or 6.

  8. In the Advanced tab for premium cache instance, configure the settings for non-TLS port, clustering, and data persistence. You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

  9. Select the Next: Tags tab or select the Next: Tags button at the bottom of the page.

  10. Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.

  11. Select Review + create. You're taken to the Review + create tab where Azure validates your configuration.

  12. After the green Validation passed message appears, select Create.

It takes a while for the cache to create. You can monitor progress on the Azure Cache for Redis Overview page. When Status shows as Running, the cache is ready to use.

Retrieve host name, ports, and access keys from the Azure portal

To connect to an Azure Cache for Redis instance, cache clients need the host name, ports, and a key for the cache. Some clients might refer to these items by slightly different names. You can get the host name, ports, and keys from the Azure portal.

  • To get the access keys, from your cache left navigation, select Access keys.

    Azure Cache for Redis keys

  • To get the host name and ports, from your cache left navigation, select Properties. The host name is of the form <DNS name>.redis.cache.windows.net.

    Azure Cache for Redis properties

Setting up the working environment

Depending on your operating system, add environment variables for your Host name and Primary access key. Open a command prompt, or a terminal window, and set up the following values:

set REDISCACHEHOSTNAME=<YOUR_HOST_NAME>.redis.cache.windows.net
set REDISCACHEKEY=<YOUR_PRIMARY_ACCESS_KEY>
export REDISCACHEHOSTNAME=<YOUR_HOST_NAME>.redis.cache.windows.net
export REDISCACHEKEY=<YOUR_PRIMARY_ACCESS_KEY>

Replace the placeholders with the following values:

  • <YOUR_HOST_NAME>: The DNS host name, obtained from the Properties section of your Azure Cache for Redis resource in the Azure portal.
  • <YOUR_PRIMARY_ACCESS_KEY>: The primary access key, obtained from the Access keys section of your Azure Cache for Redis resource in the Azure portal.

Create a new Java app

Using Maven, generate a new quickstart app:

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.3 -DgroupId=example.demo -DartifactId=redistest -Dversion=1.0

Change to the new redistest project directory.

Open the pom.xml file and add a dependency for Jedis:

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.2.0</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>

Save the pom.xml file.

Open App.java and replace the code with the following code:

package example.demo;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;

/**
 * Redis test
 *
 */
public class App 
{
    public static void main( String[] args )
    {

        boolean useSsl = true;
        String cacheHostname = System.getenv("REDISCACHEHOSTNAME");
        String cachekey = System.getenv("REDISCACHEKEY");

        // Connect to the Azure Cache for Redis over the TLS/SSL port using the key.
        JedisShardInfo shardInfo = new JedisShardInfo(cacheHostname, 6380, useSsl);
        shardInfo.setPassword(cachekey); /* Use your access key. */
        Jedis jedis = new Jedis(shardInfo);      

        // Perform cache operations using the cache connection object...

        // Simple PING command        
        System.out.println( "\nCache Command  : Ping" );
        System.out.println( "Cache Response : " + jedis.ping());

        // Simple get and put of integral data types into the cache
        System.out.println( "\nCache Command  : GET Message" );
        System.out.println( "Cache Response : " + jedis.get("Message"));

        System.out.println( "\nCache Command  : SET Message" );
        System.out.println( "Cache Response : " + jedis.set("Message", "Hello! The cache is working from Java!"));

        // Demonstrate "SET Message" executed as expected...
        System.out.println( "\nCache Command  : GET Message" );
        System.out.println( "Cache Response : " + jedis.get("Message"));

        // Get the client list, useful to see if connection list is growing...
        System.out.println( "\nCache Command  : CLIENT LIST" );
        System.out.println( "Cache Response : " + jedis.clientList());

        jedis.close();
    }
}

This code shows you how to connect to an Azure Cache for Redis instance using the cache host name and key environment variables. The code also stores and retrieves a string value in the cache. The PING and CLIENT LIST commands are also executed.

Save App.java.

Build and run the app

Execute the following Maven command to build and run the app:

mvn compile
mvn exec:java -D exec.mainClass=example.demo.App

In the example below, you can see the Message key previously had a cached value, which was set using the Redis Console in the Azure portal. The app updated that cached value. The app also executed the PING and CLIENT LIST commands.

Azure Cache for Redis app completed

Clean up resources

If you will be continuing to the next tutorial, you can keep the resources created in this quickstart and reuse them.

Otherwise, if you are finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.

Important

Deleting a resource group is irreversible and that the resource group and all the resources in it are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources. If you created the resources for hosting this sample inside an existing resource group that contains resources you want to keep, you can delete each resource individually on the left instead of deleting the resource group.

  1. Sign in to the Azure portal and select Resource groups.

  2. In the Filter by name textbox, type the name of your resource group. The instructions for this article used a resource group named TestResources. On your resource group in the result list, select ... then Delete resource group.

    Azure resource group deleted

  3. You will be asked to confirm the deletion of the resource group. Type the name of your resource group to confirm, and select Delete.

After a few moments, the resource group and all of its contained resources are deleted.

Next steps

In this quickstart, you learned how to use Azure Cache for Redis from a Java application. Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.