Quickstart: Use Azure Cache for Redis with a Java app

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

Skip to the code

This quickstart uses the Maven archetype feature to generate scaffolding for a Java app. The quickstart describes how to configure the code to create a working app that connects to Azure Cache for Redis.

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

Prerequisites

Create a cache

  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 Get Started page, type Azure Cache for Redis in the search box. Then, select Create.

    Screenshot of the Azure Marketplace with Azure Cache for Redis in the search box and create is highlighted with a red box.

  3. On the New Redis Cache page, configure the settings for your 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 is <DNS name>.redis.cache.chinacloudapi.cn.
    Location Drop down and select a location. Select a region near other services that use your cache.
    Cache SKU Drop down and select a SKU. The SKU determines the size, performance, and features parameters that are available for the cache. For more information, see Azure Cache for Redis Overview.
    Cache size Drop down and select a size of your 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 to see the Advanced tab.

    Screenshot showing the Advanced tab in the working pane and the available option to select.

    • For Basic or Standard caches, toggle the selection for a non-TLS port. You can also select if you want to enable Microsoft Entra Authentication.
    • For a Premium cache, configure the settings for non-TLS port, clustering, managed identity, and data persistence. You can also select if you want to enable Microsoft Entra Authentication.
  7. Select the Next: Tags tab or select the Next: Tags button at the bottom of the page.

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

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

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

It takes a while for a 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.

Get the host name, ports, and access key

To connect to your Azure Cache for Redis server, the cache client needs the cache's host name, ports, and an access key. Some clients might refer to these items by using slightly different names. You can get the host name, ports, and keys in the Azure portal.

  • To get an access key for your cache:

    1. In the Azure portal, go to your cache.
    2. On the service menu, under Settings, select Authentication.
    3. On the Authentication pane, select the Access keys tab.
    4. To copy the value for an access key, select the Copy icon in the key field.

    Screenshot that shows how to find and copy an access key for an instance of Azure Cache for Redis.

  • To get the host name and ports for your cache:

    1. In the Azure portal, go to your cache.
    2. On the service menu, select Overview.
    3. Under Essentials, for Host name, select the Copy icon to copy the host name value. The host name value has the form <DNS name>.redis.cache.chinacloudapi.cn.
    4. For Ports, select the Copy icon to copy the port values.

    Screenshot that shows how to find and copy the host name and ports for an instance of Azure Cache for Redis.

Set up the working environment

Depending on your operating system, add environment variables for host name and primary access key that you noted earlier. In a Command Prompt window or terminal window, set the following values:

export REDISCACHEHOSTNAME=<your-host-name>.redis.cache.chinacloudapi.cn
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.

Review the Java sample

In this sample, you use Maven to run the quickstart app.

  1. Go to the new redistest project directory.

  2. Open the pom.xml file. In the file, verify that a dependency for Jedis appears:

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>4.1.0</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
    
  3. Close the pom.xml file.

  4. Open App.java and verify that the following code appears:

    package example.demo;
    
    import redis.clients.jedis.DefaultJedisClientConfig;
    import redis.clients.jedis.Jedis;
    
    /**
     * 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.
            Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
                .password(cachekey)
                .ssl(useSsl)
                .build());
    
            // Perform cache operations by 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 by 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.

  5. Close App.java.

Build and run the app

  1. Set the environment variables as noted earlier:

    export REDISCACHEHOSTNAME=<your-host-name>.redis.cache.chinacloudapi.cn
    export REDISCACHEKEY=<your-primary-access-key>
    
  2. To build and run the app, run the following Maven command:

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

In the following output, you can see that the Message key previously had a cached value. The value was updated to a new value by using jedis.set. The app also executed the PING and CLIENT LIST commands.

Cache Command  : Ping
Cache Response : PONG

Cache Command  : GET Message
Cache Response : Hello! The cache is working from Java!

Cache Command  : SET Message
Cache Response : OK

Cache Command  : GET Message
Cache Response : Hello! The cache is working from Java!

Cache Command  : CLIENT LIST
Cache Response : id=777430 addr=             :58989 fd=22 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 ow=0 owmem=0 events=r cmd=client numops=6

Clean up resources

If you want to continue to use the resources you created in this article, keep the resource group.

Otherwise, to avoid charges related to the resources, if you're finished using the resources, you can delete the Azure resource group that you created.

Warning

Deleting a resource group is irreversible. When you delete a resource group, all the resources in the resource group are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources. If you created the resources inside an existing resource group that has resources you want to keep, you can delete each resource individually instead of deleting the resource group.

Delete a resource group

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

  2. Select the resource group to delete.

    If there are many resource groups, in Filter for any field, enter the name of the resource group you created to complete this article. In the list of search results, select the resource group.

    Screenshot that shows a list of resource groups to choose from to delete.

  3. Select Delete resource group.

  4. In the Delete a resource group pane, enter the name of your resource group to confirm, and then select Delete.

    Screenshot that shows a box that requires entering the resource name to confirm deletion.

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