Skip to content

Commit 235f7d8

Browse files
committed
Refined indents
1 parent 3dabfa1 commit 235f7d8

File tree

1 file changed

+135
-150
lines changed

1 file changed

+135
-150
lines changed

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

Lines changed: 135 additions & 150 deletions
Original file line numberDiff line numberDiff line change
@@ -47,70 +47,69 @@ npm install @azure/identity
4747

4848
### Create a new Node.js app using Microsoft Entra ID
4949

50-
1.Add environment variables for your **Host name** and **Service Principal ID**, which is the object ID your Microsoft Entra ID service principal or user. In the Azure portal, this is shown as the _Username_.
50+
1. Add environment variables for your **Host name** and **Service Principal ID**, which is the object ID of your Microsoft Entra ID service principal or user. In the Azure portal, this is shown as the _Username_.
5151

52-
```cmd
53-
set AZURE_CACHE_FOR_REDIS_HOST_NAME=contosoCache
54-
set REDIS_SERVICE_PRINCIPAL_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
55-
```
52+
```cmd
53+
set AZURE_CACHE_FOR_REDIS_HOST_NAME=contosoCache
54+
set REDIS_SERVICE_PRINCIPAL_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
55+
```
5656
5757
1. Create a new script file named _redistest.js_.
58-
1. Add the following example JavaScript to the file.
5958
60-
```javascript
61-
const { createClient } = require("redis");
62-
const { DefaultAzureCredential } = require("@azure/identity");
63-
64-
async function main() {
65-
// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.
66-
const credential = new DefaultAzureCredential();
67-
const redisScope = "https://redis.azure.com/.default";
68-
69-
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
70-
let accessToken = await credential.getToken(redisScope);
71-
console.log("access Token", accessToken);
72-
73-
// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.
74-
const cacheConnection = createClient({
75-
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
76-
password: accessToken.token,
77-
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
78-
pingInterval: 100000,
79-
socket: {
80-
tls: true,
81-
keepAlive: 0
82-
},
83-
});
84-
85-
cacheConnection.on("error", (err) => console.log("Redis Client Error", err));
86-
await cacheConnection.connect();
87-
88-
// PING command
89-
console.log("\nCache command: PING");
90-
console.log("Cache response : " + await cacheConnection.ping());
91-
92-
// SET
93-
console.log("\nCache command: SET Message");
94-
console.log("Cache response : " + await cacheConnection.set("Message",
95-
"Hello! The cache is working from Node.js!"));
96-
97-
// GET
98-
console.log("\nCache command: GET Message");
99-
console.log("Cache response : " + await cacheConnection.get("Message"));
100-
101-
// Client list, useful to see if connection list is growing...
102-
console.log("\nCache command: CLIENT LIST");
103-
console.log("Cache response : " + await cacheConnection.sendCommand(["CLIENT", "LIST"]));
104-
105-
cacheConnection.disconnect();
106-
107-
return "Done"
108-
}
109-
110-
main().then((result) => console.log(result)).catch(ex => console.log(ex));
111-
```
59+
1. Add the following example JavaScript to the file. 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. For more examples of using Redis with the [node-redis](https://github.com/redis/node-redis) client, see [https://redis.js.org/](https://redis.js.org/).
11260
113-
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. For more examples of using Redis with the [node-redis](https://github.com/redis/node-redis) client, see [https://redis.js.org/](https://redis.js.org/).
61+
```javascript
62+
const { createClient } = require("redis");
63+
const { DefaultAzureCredential } = require("@azure/identity");
64+
65+
async function main() {
66+
// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.
67+
const credential = new DefaultAzureCredential();
68+
const redisScope = "https://redis.azure.com/.default";
69+
70+
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
71+
let accessToken = await credential.getToken(redisScope);
72+
console.log("access Token", accessToken);
73+
74+
// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.
75+
const cacheConnection = createClient({
76+
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
77+
password: accessToken.token,
78+
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
79+
pingInterval: 100000,
80+
socket: {
81+
tls: true,
82+
keepAlive: 0
83+
},
84+
});
85+
86+
cacheConnection.on("error", (err) => console.log("Redis Client Error", err));
87+
await cacheConnection.connect();
88+
89+
// PING command
90+
console.log("\nCache command: PING");
91+
console.log("Cache response : " + await cacheConnection.ping());
92+
93+
// SET
94+
console.log("\nCache command: SET Message");
95+
console.log("Cache response : " + await cacheConnection.set("Message",
96+
"Hello! The cache is working from Node.js!"));
97+
98+
// GET
99+
console.log("\nCache command: GET Message");
100+
console.log("Cache response : " + await cacheConnection.get("Message"));
101+
102+
// Client list, useful to see if connection list is growing...
103+
console.log("\nCache command: CLIENT LIST");
104+
console.log("Cache response : " + await cacheConnection.sendCommand(["CLIENT", "LIST"]));
105+
106+
cacheConnection.disconnect();
107+
108+
return "Done"
109+
}
110+
111+
main().then((result) => console.log(result)).catch(ex => console.log(ex));
112+
```
114113
115114
1. Run the script with Node.js.
116115
@@ -141,83 +140,84 @@ This code shows you how to connect to an Azure Cache for Redis instance using th
141140
142141
## Create a sample JavaScript app with reauthentication
143142
144-
Microsoft Entra ID access tokens have a limited lifespan, [averaging 75 minutes](../../entra/identity-platform/configurable-token-lifetimes#token-lifetime-policies-for-access-saml-and-id-tokens). In order to maintain a connection to your cache, you need to refresh the token. This example demonstrates how to do this using JavaScript.
143+
Microsoft Entra ID access tokens have a limited lifespan, [averaging 75 minutes](/entra/identity-platform/configurable-token-lifetimes#token-lifetime-policies-for-access-saml-and-id-tokens). In order to maintain a connection to your cache, you need to refresh the token. This example demonstrates how to do this using JavaScript.
145144
146145
1. Create a new script file named _redistestreauth.js_.
147-
1. Add the following example JavaScript to the file.
148146
149-
```javascript
150-
const { createClient } = require("redis");
151-
const { DefaultAzureCredential } = require("@azure/identity");
152-
153-
async function returnPassword(credential) {
154-
const redisScope = "https://redis.azure.com/.default";
155-
156-
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
157-
return credential.getToken(redisScope);
158-
}
159-
160-
async function main() {
161-
// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.
162-
const credential = new DefaultAzureCredential();
163-
let accessToken = await returnPassword(credential);
164-
165-
// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.
166-
let cacheConnection = createClient({
167-
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
168-
password: accessToken.token,
169-
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
170-
pingInterval: 100000,
171-
socket: {
172-
tls: true,
173-
keepAlive: 0
174-
},
175-
});
176-
177-
cacheConnection.on("error", (err) => console.log("Redis Client Error", err));
178-
await cacheConnection.connect();
179-
180-
for (let i = 0; i < 3; i++) {
181-
try {
182-
// PING command
183-
console.log("\nCache command: PING");
184-
console.log("Cache response : " + await cacheConnection.ping());
185-
186-
// SET
187-
console.log("\nCache command: SET Message");
188-
console.log("Cache response : " + await cacheConnection.set("Message",
189-
"Hello! The cache is working from Node.js!"));
190-
191-
// GET
192-
console.log("\nCache command: GET Message");
193-
console.log("Cache response : " + await cacheConnection.get("Message"));
147+
1. Add the following example JavaScript to the file.
194148
195-
// Client list, useful to see if connection list is growing...
196-
console.log("\nCache command: CLIENT LIST");
197-
console.log("Cache response : " + await cacheConnection.sendCommand(["CLIENT", "LIST"]));
198-
break;
199-
} catch (e) {
200-
console.log("error during redis get", e.toString());
201-
if ((accessToken.expiresOnTimestamp <= Date.now())|| (redis.status === "end" || "close") ) {
202-
await redis.disconnect();
203-
accessToken = await returnPassword(credential);
204-
cacheConnection = createClient({
205-
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
206-
password: accessToken.token,
207-
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
208-
pingInterval: 100000,
209-
socket: {
210-
tls: true,
211-
keepAlive: 0
212-
},
213-
});
149+
```javascript
150+
const { createClient } = require("redis");
151+
const { DefaultAzureCredential } = require("@azure/identity");
152+
153+
async function returnPassword(credential) {
154+
const redisScope = "https://redis.azure.com/.default";
155+
156+
// Fetch a Microsoft Entra token to be used for authentication. This token will be used as the password.
157+
return credential.getToken(redisScope);
158+
}
159+
160+
async function main() {
161+
// Construct a Token Credential from Identity library, e.g. ClientSecretCredential / ClientCertificateCredential / ManagedIdentityCredential, etc.
162+
const credential = new DefaultAzureCredential();
163+
let accessToken = await returnPassword(credential);
164+
165+
// Create redis client and connect to the Azure Cache for Redis over the TLS port using the access token as password.
166+
let cacheConnection = createClient({
167+
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
168+
password: accessToken.token,
169+
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
170+
pingInterval: 100000,
171+
socket: {
172+
tls: true,
173+
keepAlive: 0
174+
},
175+
});
176+
177+
cacheConnection.on("error", (err) => console.log("Redis Client Error", err));
178+
await cacheConnection.connect();
179+
180+
for (let i = 0; i < 3; i++) {
181+
try {
182+
// PING command
183+
console.log("\nCache command: PING");
184+
console.log("Cache response : " + await cacheConnection.ping());
185+
186+
// SET
187+
console.log("\nCache command: SET Message");
188+
console.log("Cache response : " + await cacheConnection.set("Message",
189+
"Hello! The cache is working from Node.js!"));
190+
191+
// GET
192+
console.log("\nCache command: GET Message");
193+
console.log("Cache response : " + await cacheConnection.get("Message"));
194+
195+
// Client list, useful to see if connection list is growing...
196+
console.log("\nCache command: CLIENT LIST");
197+
console.log("Cache response : " + await cacheConnection.sendCommand(["CLIENT", "LIST"]));
198+
break;
199+
} catch (e) {
200+
console.log("error during redis get", e.toString());
201+
if ((accessToken.expiresOnTimestamp <= Date.now())|| (redis.status === "end" || "close") ) {
202+
await redis.disconnect();
203+
accessToken = await returnPassword(credential);
204+
cacheConnection = createClient({
205+
username: process.env.REDIS_SERVICE_PRINCIPAL_ID,
206+
password: accessToken.token,
207+
url: `redis://${process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME}:6380`,
208+
pingInterval: 100000,
209+
socket: {
210+
tls: true,
211+
keepAlive: 0
212+
},
213+
});
214+
}
215+
}
214216
}
215217
}
216-
}
217-
}
218-
219-
main().then((result) => console.log(result)).catch(ex => console.log(ex));
220-
```
218+
219+
main().then((result) => console.log(result)).catch(ex => console.log(ex));
220+
```
221221
222222
1. Run the script with Node.js.
223223
@@ -259,15 +259,16 @@ set AZURE_CACHE_FOR_REDIS_HOST_NAME=contosoCache
259259
set AZURE_CACHE_FOR_REDIS_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
260260
```
261261

262-
## Connect to the cache
262+
### Connect to the cache
263263

264264
>[!NOTE]
265265
> Don't create a new connection for each operation in your code. Instead, reuse connections as much as possible.
266266
>
267267
268-
## Create a new Node.js app
268+
### Create a new Node.js app
269269

270270
1. Create a new script file named _redistest.js_.
271+
271272
1. Add the following example JavaScript to the file.
272273

273274
```javascript
@@ -353,23 +354,7 @@ set AZURE_CACHE_FOR_REDIS_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
353354

354355
---
355356

356-
## Clean up resources
357-
358-
If you continue to the next tutorial, 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.
359-
360-
> [!IMPORTANT]
361-
> 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.
362-
>
363-
364-
1. Sign in to the [Azure portal](https://portal.azure.com) and select **Resource groups**.
365-
366-
1. In the **Filter by name** text box, enter 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**.
367-
368-
![Delete Azure Resource group](./media/cache-nodejs-get-started/redis-cache-delete-resource-group.png)
369-
370-
1. Confirm the deletion of the resource group. Enter the name of your resource group to confirm, and select **Delete**.
371-
372-
1. After a few moments, the resource group and all of its contained resources are deleted.
357+
[!INCLUDE [cache-delete-resource-group](includes/cache-delete-resource-group.md)]
373358

374359
## Get the sample code
375360

@@ -379,4 +364,4 @@ Get the [Node.js quickstart](https://github.com/Azure-Samples/azure-cache-redis-
379364

380365
In this quickstart, you learned how to use Azure Cache for Redis from a Node.js application. Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.
381366

382-
- [Create an ASP.NET web app that uses an Azure Cache for Redis.](./cache-web-app-howto.md)
367+
- [Create an ASP.NET web app that uses an Azure Cache for Redis.](cache-web-app-howto.md)

0 commit comments

Comments
 (0)