Quickstart: Use Azure Cache for Redis in Java with Jedis Redis client
In this quickstart, you incorporate Azure Cache for Redis into a Java app using the Jedis Redis client. Your cache is a secure, dedicated cache that is accessible from any application within Azure.
Skip to the code on GitHub
Clone the repo Java quickstart on GitHub.
Prerequisites
- Azure subscription - create one for free
- Apache Maven
Create an Azure Managed Redis (preview) instance
To create an Azure Managed Redis (preview) instance, sign in to the Azure portal and select Create a resource.
On the New page, in the search box type Azure Cache for Redis.
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 Managed 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 name that is unique in the region. The cache name must be a string between 1 and 63 characters when combined with the cache's region name that contain only numbers, letters, or hyphens. (If the cache name is fewer than 45 characters long it should work in all currently available regions.) 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\>.\<Azure region\>.redis.azure.net
.Location Drop down and select a location. Azure Managed Redis is available in selected Azure regions. Cache type Drop down and select the performance tier and cache size. The tier determines the performance of the Redis instance, while the cache size determines the memory available to store data. For guidance on choosing the right performance tier, see Choosing the right tier Select Next: Networking and select either a public or private endpoint.
Select Next: Advanced.
Configure any Redis modules you wan to add to the instance.
By default, for a new managed cache:
- Microsoft Entra ID is enabled.
- Access Keys Authentication is disabled for security reasons.
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.
Set Clustering policy to Enterprise for a nonclustered cache, or to OSS for a clustered cache. For more information on choosing Clustering policy, see Cluster policy.
If you're using Active geo-replication, it must be configured during creation. For more information, see Configure active geo-replication for Azure Managed Redis instances.
Important
You can't change the clustering policy of an Azure Managed Redis (preview) instance after you create it. If you're using RediSearch, the Enterprise cluster policy is required, and
NoEviction
is the only eviction policy supported.Important
If you're using this cache instance in a geo-replication group, eviction policies cannot be changed after the instance is created. Be sure to know the eviction policies of your primary nodes before you create the cache. For more information on active geo-replication, see Active geo-replication prerequisites.
Important
You can't change modules after you create a cache instance. Modules must be enabled at the time you create an Azure Cache for Redis instance. There is no option to enable the configuration of a module after you create a cache.
Select Next: Tags and skip.
Select Next: Review + create.
Review the settings and select Create.
It takes several minutes for the Redis instance to create. You can monitor progress on the Azure Managed Redis Overview page. When Status shows as Running, the cache is ready to use.
Create an Azure Cache for Redis instance
To create a cache, sign in to the Azure portal. On the portal menu, select Create a resource.
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.
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. Select the Networking tab or select Next: Networking.
On the Networking tab, select a connectivity method to use for the cache.
Select the Advanced tab or select Next: Advanced.
On the Advanced pane, verify or select an authentication method based on the following information:
- 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.
(Optional) Select the Tags tab or select Next: Tags.
(Optional) On the Tags tab, enter a tag name and value if you want to categorize your cache resource.
Select the Review + create button.
On the Review + create tab, Azure automatically validates your configuration.
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.
Retrieve host name, ports, and access keys from the Azure portal
To connect your Azure Cache for Redis server, the cache client needs 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 host name and ports for your cache, select Overview from the Resource menu. The host name is of the form
<DNS name>.redis.cache.windows.net
.To get the access keys, select Authentication from the Resource menu. Then, select the Access keys tab.
Set up the working environment
The following steps show you how to set up the working environment for the Java app. You can choose to authenticate with Azure Cache for Redis using Microsoft Entra ID (recommended) or access keys.
export REDIS_CACHE_HOSTNAME=<your-host-name>.redis.cache.windows.net
export USER_NAME=<user-name>
export REDIS_CACHE_PORT=10000
export REDIS_CACHE_HOSTNAME=<your-host-name>.redis.cache.windows.net
export USER_NAME=<user-name>
export REDIS_CACHE_PORT=6380
Replace the placeholders with the following values:
<your-host-name>
: The DNS host name. To get the host name and ports for your cache, select Overview from the Resource menu. The host name is of the form<DNS name>.redis.cache.windows.net
.<user-name>
: Object ID of your managed identity or service principal.You can get the user name by using the following steps:
Create a new Java app
Use maven to generate a new quickstart app:
mvn archetype:generate \ -DarchetypeGroupId=org.apache.maven.archetypes \ -DarchetypeArtifactId=maven-archetype-quickstart \ -DarchetypeVersion=1.3 \ -DinteractiveMode=false \ -DgroupId=example.demo \ -DartifactId=redis-jedis-test \ -Dversion=1.0
Change to the new redis-jedis-test project directory.
Open the pom.xml file. In the file, you see a dependency for Jedis:
<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.15.0</version> <!-- {x-version-update;com.azure:azure-identity;dependency} --> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>5.2.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} --> </dependency>
Close the pom.xml file.
Open App.java and see the code with the following code:
package example.demo; import com.azure.identity.DefaultAzureCredential; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.core.credential.TokenRequestContext; import redis.clients.jedis.DefaultJedisClientConfig; import redis.clients.jedis.Jedis; /** * Redis test * */ public class App { public static void main( String[] args ) { boolean useSsl = true; //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. This token will be used as the password. String token = defaultAzureCredential .getToken(new TokenRequestContext() .addScopes("https://redis.azure.com/.default")).block().getToken(); String cacheHostname = System.getenv("REDIS_CACHE_HOSTNAME"); String username = System.getenv("USER_NAME"); int port = Integer.parseInt(System.getenv().getOrDefault("REDIS_CACHE_PORT", "6380")); // Connect to the Azure Cache for Redis over the TLS/SSL port using the key. Jedis jedis = new Jedis(cacheHostname, port, DefaultJedisClientConfig.builder() .password(token) // Microsoft Entra access token as password is required. .user(username) // Username is Required .ssl(useSsl) // SSL Connection is Required .build()); // 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
andCLIENT LIST
commands are also executed.Close the App.java file.
Build and run the app
Execute the following Maven command to build and run the app:
mvn compile 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 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 plan to continue with the next tutorial, you can keep the resources created in this quickstart and reuse them.
Otherwise, if you're 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 instead of deleting the resource group.
Sign in to the Azure portal and select Resource groups.
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 Test Resources then Delete resource group.Type the name of your resource group to confirm deletion and then 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.