Quickstart: Use Azure Cache for Redis with a Java app and a Redisson Redis client

In this quickstart, you incorporate Azure Cache for Redis into a Java app by using the Redisson Redis client and the Java Community Practice (JCP) standard JCache API. These services give you access to a secure, dedicated cache that is accessible from any application in Azure.

This article describes two options to select the Azure identity to use for the Redis connection:

  • Authentication by using a Redis key
  • Authentication by using Microsoft Entra ID

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. On the portal menu, select Create a resource.

    Sceenshot that shows the Create a resource option highlighted on the left navigation pane in the Azure portal.

  2. On the Get Started pane, enter Azure Cache for Redis in the search bar. In the search results, find Azure Cache for Redis, and then select Create.

    Screenshot that shows Azure Marketplace with Azure Cache for Redis in the search box, and the Create button is highlighted.

  3. On the New Redis Cache pane, on the Basics tab, configure the following settings for your cache:

    Setting Action Description
    Subscription Select your Azure subscription. The subscription to use to create the new instance of Azure Cache for Redis.
    Resource group Select a resource group, or select Create new and enter a new resource group name. A 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 of 1 to 63 characters that contains only numbers, letters, and hyphens. The name must start and end with a number or letter, and it can't contain consecutive hyphens. Your cache instance's host name is \<DNS name>.redis.cache.windows.net.
    Location Select a location. An Azure region that is near other services that use your cache.
    Cache SKU Select a SKU. The SKU determines the size, performance, and feature parameters that are available for the cache. For more information, see Azure Cache for Redis overview.
    Cache size Select a cache size. For more information, see Azure Cache for Redis overview.
  4. Select the Networking tab or select Next: Networking.

  5. On the Networking tab, select a connectivity method to use for the cache.

  6. Select the Advanced tab or select Next: Advanced.

  7. On the Advanced pane, verify or select an authentication method based on the following information:

    Screenshot showing the Advanced pane and the available options to select.

    • By default, for a new Basic, Standard, or Premium cache, Microsoft Entra Authentication is enabled and Access Keys Authentication is disabled.
    • For Basic or Standard caches, you can choose the selection for a non-TLS port.
    • For Standard and Premium caches, you can choose to enable availability zones. You can't disable availability zones after the cache is created.
    • For a Premium cache, configure the settings for non-TLS port, clustering, managed identity, and data persistence.

    Important

    For optimal security, we recommend that you use Microsoft Entra ID with managed identities to authorize requests against your cache if possible. Authorization by using Microsoft Entra ID and managed identities provides superior security and ease of use over shared access key authorization. For more information about using managed identities with your cache, see Use Microsoft Entra ID for cache authentication.

  8. (Optional) Select the Tags tab or select Next: Tags.

  9. (Optional) On the Tags tab, enter a tag name and value if you want to categorize your cache resource.

  10. Select the Review + create button.

    On the Review + create tab, Azure automatically validates your configuration.

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

A new cache deployment occurs over several minutes. You can monitor the progress of the deployment on the Azure Cache for Redis Overview pane. When Status displays 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.windows.net.
    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

The steps in this section show you two options for selecting an Azure identity to use for the Redis connection. The sample code looks at the value of the AUTH_TYPE environment variable, and then takes action based on the value.

Authenticate by using a Redis key

Depending on your operating system, add environment variables to hold your cache's host name and primary access key. In a Command Prompt window or terminal window, set the following values:

export REDIS_CACHE_HOSTNAME=<your-host-name>.redis.cache.windows.net
export REDIS_CACHE_KEY=<your-primary-access-key>
export AUTH_TYPE=RedisKey

In the preceding code, 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.

Authenticate by using Microsoft Entra ID

Depending on your operating system, add environment variables to hold your cache's host name and user name. In a Command Prompt window or terminal window, set up the following values:

export REDIS_CACHE_HOSTNAME=<your-host-name>.redis.cache.windows.net
export USER_NAME=<user-name>
export AUTH_TYPE=MicrosoftEntraID

In the preceding code, 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.

  • <user-name>: The object ID of your managed identity or service principal.

    To get the user name:

    1. In the Azure portal, go to your Azure Cache for Redis instance.

    2. On the service menu, select Data Access Configuration.

    3. On the Redis Users tab, find the Username column and copy the value.

      Screenshot of the Azure portal that shows the Azure Cache for Redis Data Access Configuration page with the Redis Users tab and a Username value highlighted.

Create a new Java app

Generate a new quickstart app by using Maven:

mvn archetype:generate \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-quickstart \
    -DarchetypeVersion=1.3 \
    -DinteractiveMode=false \
    -DgroupId=example.demo \
    -DartifactId=redis-redisson-test \
    -Dversion=1.0

Go to the new redis-redisson-test project directory.

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

    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-identity</artifactId>
        <version>1.8.2</version>
    </dependency>

    <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson</artifactId>
        <version>3.24.3</version>
    </dependency>

Save the pom.xml file.

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

package example.demo;

import com.azure.core.credential.TokenRequestContext;
import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.jcache.configuration.RedissonConfiguration;

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.Configuration;
import javax.cache.configuration.MutableConfiguration;
import java.time.LocalDateTime;


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

        Config redissonconfig = getConfig();

        RedissonClient redissonClient = Redisson.create(redissonconfig);

        MutableConfiguration<String, String> jcacheConfig = new MutableConfiguration<>();
        Configuration<String, String> config = RedissonConfiguration.fromInstance(redissonClient, jcacheConfig);

        // Perform cache operations using JCache
        CacheManager manager = Caching.getCachingProvider().getCacheManager();
        Cache<String, String> map = manager.createCache("test", config);

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

        System.out.println("\nCache Command  : SET Message");
        map.put("Message",
            String.format("Hello! The cache is working from Java! %s", LocalDateTime.now()));

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

        redissonClient.shutdown();
    }

    private static Config getConfig(){
        if ("MicrosoftEntraID".equals(System.getenv("AUTH_TYPE"))) {
            System.out.println("Auth with Microsoft Entra ID");
            return getConfigAuthWithAAD();
        } else if ("RedisKey".equals(System.getenv("AUTH_TYPE"))) {
            System.out.println("Auth with Redis key");
            return getConfigAuthWithKey();
        }
        System.out.println("Auth with Redis key");
        return getConfigAuthWithKey();
    }

    private static Config getConfigAuthWithKey() {
        // Connect to the Azure Cache for Redis over the TLS/SSL port using the key
        Config redissonconfig = new Config();
        redissonconfig.useSingleServer().setPassword(System.getenv("REDIS_CACHE_KEY"))
            .setAddress(String.format("rediss://%s:6380", System.getenv("REDIS_CACHE_HOSTNAME")));
        return redissonconfig;
    }

    private static Config getConfigAuthWithAAD() {
        //Construct a Token Credential from Identity library, e.g. DefaultAzureCredential / ClientSecretCredential / Client CertificateCredential / ManagedIdentityCredential etc.
        DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();

        // Fetch a Microsoft Entra token to be used for authentication.
        String token = defaultAzureCredential
            .getToken(new TokenRequestContext()
                .addScopes("acca5fbb-b7e4-4009-81f1-37e38fd66d78/.default")).block().getToken();

        // Connect to the Azure Cache for Redis over the TLS/SSL port using the key
        Config redissonconfig = new Config();
        redissonconfig.useSingleServer()
            .setAddress(String.format("rediss://%s:6380", System.getenv("REDIS_CACHE_HOSTNAME")))
            .setUsername(System.getenv("USER_NAME")) // (Required) Username is Object ID of your managed identity or service principal
            .setPassword(token); // Microsoft Entra access token as password is required.
        return redissonconfig;
    }

}

This code shows you how to connect to an Azure Cache for Redis instance by using Microsoft Entra ID with the JCache API support from the Redisson client library. The code also stores and retrieves a string value in the cache. For more information, see the JCache specification.

Save App.java.

Build and run the app

To build and run the app, run the following Maven command:

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

In the following output, you can see that the Message key previously had a cached value that was set in the last run. The app updated that cached value.

Cache Command  : GET Message
Cache Response : Hello! The cache is working from Java! 2023-12-05T15:13:11.398873

Cache Command  : SET Message

Cache Command  : GET Message
Cache Response : Hello! The cache is working from Java! 2023-12-05T15:45:45.748667

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.