title | description | author | ms.author | ms.reviewer | ms.date | ms.topic | ms.devlang | ms.custom | zone_pivot_groups | appliesto | ||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Quickstart: Use Azure Cache for Redis in Java | In this quickstart, you create a new Java app that uses Azure Cache for Redis | KarlErickson | karler | zhihaoguo | 01/04/2022 | quickstart | java | devx-track-java, devx-track-javaee, mode-api, mvc, devx-track-extended-java, ignite-2024 | redis-type |
|
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.
Clone the repo Java quickstart on GitHub.
- Azure subscription - create one for free
- Apache Maven
::: zone pivot="azure-managed-redis"
[!INCLUDE managed-redis-create]
::: zone-end
::: zone pivot="azure-cache-redis"
[!INCLUDE redis-cache-create]
[!INCLUDE redis-cache-access-keys]
::: zone-end
[!INCLUDE redis-setup-working-environment]
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>
[!INCLUDE redis-access-key-alert]
<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:
packageexample.demo; importcom.azure.identity.DefaultAzureCredential; importcom.azure.identity.DefaultAzureCredentialBuilder; importcom.azure.core.credential.TokenRequestContext; importredis.clients.jedis.DefaultJedisClientConfig; importredis.clients.jedis.Jedis; /** * Redis test * */publicclassApp { publicstaticvoidmain( String[] args ) { booleanuseSsl = true; //Construct a Token Credential from Identity library, e.g. DefaultAzureCredential / ClientSecretCredential / Client CertificateCredential / ManagedIdentityCredential etc.DefaultAzureCredentialdefaultAzureCredential = newDefaultAzureCredentialBuilder().build(); // Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.Stringtoken = defaultAzureCredential .getToken(newTokenRequestContext() .addScopes("https://redis.azure.com/.default")).block().getToken(); StringcacheHostname = System.getenv("REDIS_CACHE_HOSTNAME"); Stringusername = System.getenv("USER_NAME"); intport = Integer.parseInt(System.getenv().getOrDefault("REDIS_CACHE_PORT", "6380")); // Connect to the Azure Cache for Redis over the TLS/SSL port using the key.Jedisjedis = newJedis(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 commandSystem.out.println( "\nCache Command : Ping" ); System.out.println( "Cache Response : " + jedis.ping()); // Simple get and put of integral data types into the cacheSystem.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(); } }
packageexample.demo; importredis.clients.jedis.DefaultJedisClientConfig; importredis.clients.jedis.Jedis; /** * Redis test * */publicclassApp { publicstaticvoidmain( String[] args ) { booleanuseSsl = true; StringcacheHostname = System.getenv("REDIS_CACHE_HOSTNAME"); Stringcachekey = System.getenv("REDIS_CACHE_KEY"); intport = Integer.parseInt(System.getenv().getOrDefault("REDIS_CACHE_PORT", "6380")); // Connect to the Azure Cache for Redis over the TLS/SSL port using the key.Jedisjedis = newJedis(cacheHostname, port, DefaultJedisClientConfig.builder() .password(cachekey) .ssl(useSsl) .build()); // Perform cache operations using the cache connection object...// Simple PING commandSystem.out.println( "\nCache Command : Ping" ); System.out.println( "Cache Response : " + jedis.ping()); // Simple get and put of integral data types into the cacheSystem.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.
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
[!INCLUDE redis-cache-resource-group-clean-up]
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.