Skip to content

Commit f476a5c

Browse files
authored
Merge pull request #292172 from backwind1233/sfi_wave3_redis_6555
SFI: Support Microsoft Entra ID Authentication
2 parents 144012c + 12e725f commit f476a5c

File tree

6 files changed

+357
-314
lines changed

6 files changed

+357
-314
lines changed

articles/azure-cache-for-redis/cache-java-get-started.md

Lines changed: 120 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@ author: KarlErickson
55
ms.author: zhihaoguo
66
ms.date: 01/04/2022
77
ms.topic: quickstart
8-
98
ms.devlang: java
109
ms.custom: devx-track-java, devx-track-javaee, mode-api, mvc, devx-track-extended-java, ignite-2024
1110
---
1211

13-
# Quickstart: Use Azure Cache for Redis in Java
12+
# Quickstart: Use Azure Cache for Redis in Java with Jedis Redis client
1413

1514
In this quickstart, you incorporate Azure Cache for Redis into a Java app using the [Jedis](https://github.com/xetorthio/jedis) Redis client. Your cache is a secure, dedicated cache that is accessible from any application within Azure.
1615

@@ -27,148 +26,192 @@ Clone the repo [Java quickstart](https://github.com/Azure-Samples/azure-cache-re
2726

2827
[!INCLUDE [redis-cache-create](~/reusable-content/ce-skilling/azure/includes/azure-cache-for-redis/includes/redis-cache-create.md)]
2928

30-
[!INCLUDE [redis-cache-access-keys](includes/redis-cache-access-keys.md)]
31-
3229
## Set up the working environment
3330

34-
Depending on your operating system, add environment variables for your **Host name** and **Primary access key** that you noted previously. Open a command prompt, or a terminal window, and set up the following values:
35-
36-
### [Linux](#tab/bash)
37-
38-
```bash
39-
export REDISCACHEHOSTNAME=<your-host-name>.redis.cache.windows.net
40-
export REDISCACHEKEY=<your-primary-access-key>
41-
```
31+
[!INCLUDE [redis-setup-working-environment](includes/redis-setup-working-environment.md)]
4232

43-
### [Windows](#tab/cmd)
33+
## Create a new Java app
4434

45-
```cmd
46-
set REDISCACHEHOSTNAME=<your-host-name>.redis.cache.windows.net
47-
set REDISCACHEKEY=<your-primary-access-key>
48-
```
35+
1. Use maven to generate a new quickstart app:
4936

50-
---
37+
```xml
38+
mvn archetype:generate \
39+
-DarchetypeGroupId=org.apache.maven.archetypes \
40+
-DarchetypeArtifactId=maven-archetype-quickstart \
41+
-DarchetypeVersion=1.3 \
42+
-DinteractiveMode=false \
43+
-DgroupId=example.demo \
44+
-DartifactId=redis-jedis-test \
45+
-Dversion=1.0
46+
```
5147

52-
Replace the placeholders with the following values:
48+
1. Change to the new **redis-jedis-test** project directory.
49+
1. Open the **pom.xml** file. In the file, you see a dependency for [Jedis](https://github.com/xetorthio/jedis):
5350

54-
- `<your-host-name>`: The DNS host name, obtained from the *Properties* section of your Azure Cache for Redis resource in the Azure portal.
55-
- `<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.
51+
### [Microsoft Entra ID authentication (recommended)](#tab/entraid)
5652

57-
## Understand the Java sample
53+
```xml
54+
<dependency>
55+
<groupId>com.azure</groupId>
56+
<artifactId>azure-identity</artifactId>
57+
<version>1.11.2</version> <!-- {x-version-update;com.azure:azure-identity;dependency} -->
58+
</dependency>
5859

59-
In this sample, you use Maven to run the quickstart app.
60+
<dependency>
61+
<groupId>redis.clients</groupId>
62+
<artifactId>jedis</artifactId>
63+
<version>5.1.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} -->
64+
</dependency>
65+
```
6066

61-
1. Change to the new *redistest* project directory.
67+
### [Access key authentication](#tab/accesskey)
6268

63-
1. Open the *pom.xml* file. In the file, you see a dependency for [Jedis](https://github.com/xetorthio/jedis):
69+
[!INCLUDE [redis-access-key-alert](includes/redis-access-key-alert.md)]
6470

6571
```xml
6672
<dependency>
67-
<groupId>redis.clients</groupId>
68-
<artifactId>jedis</artifactId>
69-
<version>4.1.0</version>
70-
<type>jar</type>
71-
<scope>compile</scope>
73+
<groupId>redis.clients</groupId>
74+
<artifactId>jedis</artifactId>
75+
<version>5.1.0</version> <!-- {x-version-update;redis.clients:jedis;external_dependency} -->
7276
</dependency>
7377
```
7478

75-
1. Close the *pom.xml* file.
79+
1. Close the **pom.xml** file.
80+
81+
1. Open **App.java** and see the code with the following code:
7682

77-
1. Open *App.java* and see the code with the following code:
83+
### [Microsoft Entra ID authentication (recommended)](#tab/entraid)
7884

7985
```java
8086
package example.demo;
81-
87+
88+
import com.azure.identity.DefaultAzureCredential;
89+
import com.azure.identity.DefaultAzureCredentialBuilder;
90+
import com.azure.core.credential.TokenRequestContext;
8291
import redis.clients.jedis.DefaultJedisClientConfig;
8392
import redis.clients.jedis.Jedis;
84-
93+
8594
/**
8695
* Redis test
8796
*
8897
*/
89-
public class App
98+
public class App
9099
{
91100
public static void main( String[] args )
92101
{
93-
102+
94103
boolean useSsl = true;
95-
String cacheHostname = System.getenv("REDISCACHEHOSTNAME");
96-
String cachekey = System.getenv("REDISCACHEKEY");
97-
104+
105+
//Construct a Token Credential from Identity library, e.g. DefaultAzureCredential / ClientSecretCredential / Client CertificateCredential / ManagedIdentityCredential etc.
106+
DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build();
107+
108+
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
109+
String token = defaultAzureCredential
110+
.getToken(new TokenRequestContext()
111+
.addScopes("https://redis.azure.com/.default")).block().getToken();
112+
113+
String cacheHostname = System.getenv("REDIS_CACHE_HOSTNAME");
114+
String username = System.getenv("USER_NAME");
115+
98116
// Connect to the Azure Cache for Redis over the TLS/SSL port using the key.
99117
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
100-
.password(cachekey)
101-
.ssl(useSsl)
102-
.build());
103-
118+
.password(token) // Microsoft Entra access token as password is required.
119+
.user(username) // Username is Required
120+
.ssl(useSsl) // SSL Connection is Required
121+
.build());
104122
// Perform cache operations using the cache connection object...
105-
123+
106124
// Simple PING command
107125
System.out.println( "\nCache Command : Ping" );
108126
System.out.println( "Cache Response : " + jedis.ping());
109-
127+
110128
// Simple get and put of integral data types into the cache
111129
System.out.println( "\nCache Command : GET Message" );
112130
System.out.println( "Cache Response : " + jedis.get("Message"));
113-
131+
114132
System.out.println( "\nCache Command : SET Message" );
115133
System.out.println( "Cache Response : " + jedis.set("Message", "Hello! The cache is working from Java!"));
116-
134+
117135
// Demonstrate "SET Message" executed as expected...
118136
System.out.println( "\nCache Command : GET Message" );
119137
System.out.println( "Cache Response : " + jedis.get("Message"));
120-
138+
121139
// Get the client list, useful to see if connection list is growing...
122140
System.out.println( "\nCache Command : CLIENT LIST" );
123141
System.out.println( "Cache Response : " + jedis.clientList());
124-
142+
125143
jedis.close();
126144
}
127145
}
128146
```
129147

130-
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.
131-
132-
1. Close the *App.java*.
148+
### [Access key authentication](#tab/accesskey)
133149

134-
## Build and run the app
150+
```java
151+
package example.demo;
135152

136-
1. First, if you haven't already, you must set the environment variables as noted previously.
153+
import redis.clients.jedis.DefaultJedisClientConfig;
154+
import redis.clients.jedis.Jedis;
137155

138-
### [Linux](#tab/bash)
156+
/**
157+
* Redis test
158+
*
159+
*/
160+
public class App
161+
{
162+
public static void main( String[] args )
163+
{
139164

140-
```bash
141-
export REDISCACHEHOSTNAME=<your-host-name>.redis.cache.windows.net
142-
export REDISCACHEKEY=<your-primary-access-key>
143-
```
165+
boolean useSsl = true;
166+
String cacheHostname = System.getenv("REDIS_CACHE_HOSTNAME");
167+
String cachekey = System.getenv("REDIS_CACHE_KEY");
144168

145-
### [Windows](#tab/cmd)
169+
// Connect to the Azure Cache for Redis over the TLS/SSL port using the key.
170+
Jedis jedis = new Jedis(cacheHostname, 6380, DefaultJedisClientConfig.builder()
171+
.password(cachekey)
172+
.ssl(useSsl)
173+
.build());
146174

147-
```cmd
148-
set REDISCACHEHOSTNAME=<your-host-name>.redis.cache.windows.net
149-
set REDISCACHEKEY=<your-primary-access-key>
150-
```
175+
// Perform cache operations using the cache connection object...
151176

152-
---
177+
// Simple PING command
178+
System.out.println( "\nCache Command : Ping" );
179+
System.out.println( "Cache Response : " + jedis.ping());
153180

154-
1. Execute the following Maven command to build and run the app:
181+
// Simple get and put of integral data types into the cache
182+
System.out.println( "\nCache Command : GET Message" );
183+
System.out.println( "Cache Response : " + jedis.get("Message"));
155184

156-
### [Linux](#tab/bash)
185+
System.out.println( "\nCache Command : SET Message" );
186+
System.out.println( "Cache Response : " + jedis.set("Message", "Hello! The cache is working from Java!"));
157187

158-
```bash
159-
mvn compile
160-
mvn exec:java -D exec.mainClass=example.demo.App
161-
```
188+
// Demonstrate "SET Message" executed as expected...
189+
System.out.println( "\nCache Command : GET Message" );
190+
System.out.println( "Cache Response : " + jedis.get("Message"));
162191

163-
### [Windows](#tab/cmd)
192+
// Get the client list, useful to see if connection list is growing...
193+
System.out.println( "\nCache Command : CLIENT LIST" );
194+
System.out.println( "Cache Response : " + jedis.clientList());
164195

165-
```cmd
166-
mvn compile
167-
mvn exec:java -D exec.mainClass=example.demo.App
168-
```
196+
jedis.close();
197+
}
198+
}
199+
```
169200

170201
---
171202

203+
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.
204+
205+
1. Close the **App.java** file.
206+
207+
## Build and run the app
208+
209+
Execute the following Maven command to build and run the app:
210+
211+
```bash
212+
mvn compile exec:java -D exec.mainClass=example.demo.App
213+
```
214+
172215
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.
173216

174217
```output
@@ -188,25 +231,7 @@ Cache Command : CLIENT LIST
188231
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
189232
```
190233

191-
## Clean up resources
192-
193-
If you continue to use the quickstart code, you can keep the resources created in this quickstart and reuse them.
194-
195-
Otherwise, if you're finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.
196-
197-
> [!IMPORTANT]
198-
> 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.
199-
>
200-
201-
1. Sign in to the [Azure portal](https://portal.azure.com) and select **Resource groups**.
202-
203-
1. 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**.
204-
205-
:::image type="content" source="media/cache-java-get-started/azure-cache-redis-delete-resource-group.png" alt-text="Screenshot of the Azure portal that shows the Resource groups page with the Delete resource group button highlighted." lightbox="media/cache-java-get-started/azure-cache-redis-delete-resource-group.png":::
206-
207-
1. Type the name of your resource group to confirm deletion and then select **Delete**.
208-
209-
After a few moments, the resource group and all of its contained resources are deleted.
234+
[!INCLUDE [redis-cache-resource-group-clean-up](includes/redis-cache-resource-group-clean-up.md)]
210235

211236
## Next steps
212237

0 commit comments

Comments
 (0)