Skip to content

Commit 1cf72a8

Browse files
Merge pull request #227653 from diberry/diberry/0215-redis
Azure Cache for Redis - JS - quickstart
2 parents 7707711 + 33496e0 commit 1cf72a8

File tree

2 files changed

+114
-86
lines changed

2 files changed

+114
-86
lines changed

.openpublishing.publish.config.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -913,6 +913,12 @@
913913
"url": "https://github.com/Azure-Samples/azure-cosmos-db-mongodb-python-getting-started",
914914
"branch": "main",
915915
"branch_mapping": {}
916+
},
917+
{
918+
"path_to_root": "azure-cache-redis-samples",
919+
"url": "https://github.com/Azure-Samples/azure-cache-redis-samples",
920+
"branch": "main",
921+
"branch_mapping": {}
916922
}
917923
],
918924
"branch_target_mapping": {

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

Lines changed: 108 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,19 @@
11
---
22
title: 'Quickstart: Use Azure Cache for Redis in Node.js'
3-
description: In this quickstart, you'll learn how to use Azure Cache for Redis with Node.js and node_redis.
3+
description: In this quickstart, learn how to use Azure Cache for Redis with Node.js and node_redis.
44
author: flang-msft
55
ms.service: cache
66
ms.devlang: javascript
77
ms.topic: quickstart
8-
ms.date: 02/04/2022
8+
ms.date: 02/16/2023
99
ms.author: franlanglois
10-
ms.custom: mvc, seo-javascript-september2019, seo-javascript-october2019, devx-track-js, mode-api
10+
ms.custom: mvc, seo-javascript-september2019, seo-javascript-october2019, devx-track-js, mode-api, engagement-fy23
1111
#Customer intent: As a Node.js developer, new to Azure Cache for Redis, I want to create a new Node.js app that uses Azure Cache for Redis.
1212
---
1313
# Quickstart: Use Azure Cache for Redis in Node.js
1414

1515
In this quickstart, you incorporate Azure Cache for Redis into a Node.js app to have access to a secure, dedicated cache that is accessible from any application within Azure.
1616

17-
## Skip to the code on GitHub
18-
19-
If you want to skip straight to the code, see the [Node.js quickstart](https://github.com/Azure-Samples/azure-cache-redis-samples/tree/main/quickstart/nodejs) on GitHub.
20-
2117
## Prerequisites
2218

2319
- Azure subscription - [create one for free](https://azure.microsoft.com/free/)
@@ -34,103 +30,129 @@ For examples of using other Node.js clients, see the individual documentation fo
3430
Add environment variables for your **HOST NAME** and **Primary** access key. Use these variables from your code instead of including the sensitive information directly in your code.
3531

3632
```powershell
37-
set REDISCACHEHOSTNAME=contosoCache.redis.cache.windows.net
38-
set REDISCACHEKEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
33+
set AZURE_CACHE_FOR_REDIS_HOST_NAME=contosoCache
34+
set AZURE_CACHE_FOR_REDIS_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3935
```
4036

4137
## Connect to the cache
4238

43-
The latest builds of [node_redis](https://github.com/mranney/node_redis) provide support for connecting to Azure Cache for Redis using TLS. The following example shows how to connect to Azure Cache for Redis using the TLS endpoint of 6380.
44-
45-
```js
46-
var redis = require("redis");
47-
48-
// Add your cache name and access key.
49-
var client = redis.createClient(6380, process.env.REDISCACHEHOSTNAME,
50-
{auth_pass: process.env.REDISCACHEKEY, tls: {servername: process.env.REDISCACHEHOSTNAME}});
51-
```
52-
53-
Don't create a new connection for each operation in your code. Instead, reuse connections as much as possible.
39+
The latest builds of [node_redis](https://github.com/mranney/node_redis) provide support several connection options. Don't create a new connection for each operation in your code. Instead, reuse connections as much as possible.
5440

5541
## Create a new Node.js app
5642

57-
Create a new script file named *redistest.js*. Use the command `npm install redis bluebird` to install required packages.
58-
59-
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/mranney/node_redis) client, see [https://redis.js.org/](https://redis.js.org/).
60-
61-
```js
62-
var redis = require("redis");
63-
64-
async function testCache() {
65-
66-
// Connect to the Azure Cache for Redis over the TLS port using the key.
67-
var cacheHostName = process.env.REDISCACHEHOSTNAME;
68-
var cachePassword = process.env.REDISCACHEKEY;
69-
var cacheConnection = redis.createClient({
70-
// rediss for TLS
71-
url: "rediss://" + cacheHostName + ":6380",
72-
password: cachePassword,
73-
});
74-
await cacheConnection.connect();
75-
76-
// Perform cache operations using the cache connection object...
77-
78-
// Simple PING command
79-
console.log("\nCache command: PING");
80-
console.log("Cache response : " + await cacheConnection.ping());
81-
82-
// Simple get and put of integral data types into the cache
83-
console.log("\nCache command: GET Message");
84-
console.log("Cache response : " + await cacheConnection.get("Message"));
85-
86-
console.log("\nCache command: SET Message");
87-
console.log("Cache response : " + await cacheConnection.set("Message",
88-
"Hello! The cache is working from Node.js!"));
89-
90-
// Demonstrate "SET Message" executed as expected...
91-
console.log("\nCache command: GET Message");
92-
console.log("Cache response : " + await cacheConnection.get("Message"));
93-
94-
// Get the client list, useful to see if connection list is growing...
95-
console.log("\nCache command: CLIENT LIST");
96-
console.log("Cache response : " + await cacheConnection.sendCommand(["CLIENT", "LIST"]));
97-
98-
console.log("\nDone");
99-
process.exit();
100-
}
101-
102-
testCache();
103-
```
104-
105-
Run the script with Node.js.
106-
107-
```powershell
108-
node redistest.js
109-
```
110-
111-
In the example below, you can see the `Message` key previously had a cached value, which was set using the Redis Console in the Azure portal. The app updated that cached value. The app also executed the `PING` and `CLIENT LIST` commands.
112-
113-
![Redis Cache app completed](./media/cache-nodejs-get-started/redis-cache-app-complete.png)
43+
1. Create a new script file named *redistest.js*.
44+
1. Use the command to install a redis package.
45+
46+
```bash
47+
`npm install redis`
48+
```
49+
50+
1. Add the following example JavaScript to the file.
51+
52+
53+
```javascript
54+
const redis = require("redis");
55+
56+
// Environment variables for cache
57+
const cacheHostName = process.env.AZURE_CACHE_FOR_REDIS_HOST_NAME;
58+
const cachePassword = process.env.AZURE_CACHE_FOR_REDIS_ACCESS_KEY;
59+
60+
if(!cacheHostName) throw Error("AZURE_CACHE_FOR_REDIS_HOST_NAME is empty")
61+
if(!cachePassword) throw Error("AZURE_CACHE_FOR_REDIS_ACCESS_KEY is empty")
62+
63+
async function testCache() {
64+
65+
// Connection configuration
66+
const cacheConnection = redis.createClient({
67+
// rediss for TLS
68+
url: `rediss://${cacheHostName}:6380`,
69+
password: cachePassword
70+
});
71+
72+
// Connect to Redis
73+
await cacheConnection.connect();
74+
75+
// PING command
76+
console.log("\nCache command: PING");
77+
console.log("Cache response : " + await cacheConnection.ping());
78+
79+
// GET
80+
console.log("\nCache command: GET Message");
81+
console.log("Cache response : " + await cacheConnection.get("Message"));
82+
83+
// SET
84+
console.log("\nCache command: SET Message");
85+
console.log("Cache response : " + await cacheConnection.set("Message",
86+
"Hello! The cache is working from Node.js!"));
87+
88+
// GET again
89+
console.log("\nCache command: GET Message");
90+
console.log("Cache response : " + await cacheConnection.get("Message"));
91+
92+
// Client list, useful to see if connection list is growing...
93+
console.log("\nCache command: CLIENT LIST");
94+
console.log("Cache response : " + await cacheConnection.sendCommand(["CLIENT", "LIST"]));
95+
96+
// Disconnect
97+
cacheConnection.disconnect()
98+
99+
return "Done"
100+
}
101+
102+
testCache().then((result) => console.log(result)).catch(ex => console.log(ex));
103+
```
104+
105+
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/mranney/node_redis) client, see [https://redis.js.org/](https://redis.js.org/).
106+
107+
108+
1. Run the script with Node.js.
109+
110+
```bash
111+
node redistest.js
112+
```
113+
114+
1. Example the output.
115+
116+
```console
117+
Cache command: PING
118+
Cache response : PONG
119+
120+
Cache command: GET Message
121+
Cache response : Hello! The cache is working from Node.js!
122+
123+
Cache command: SET Message
124+
Cache response : OK
125+
126+
Cache command: GET Message
127+
Cache response : Hello! The cache is working from Node.js!
128+
129+
Cache command: CLIENT LIST
130+
Cache response : id=10017364 addr=76.22.73.183:59380 fd=221 name= age=1 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 ow=0 owmem=0 events=r cmd=client user=default numops=6
131+
132+
Done
133+
```
114134
115135
## Clean up resources
116136
117-
If you continue to the next tutorial, can keep the resources created in this quickstart and reuse them.
118-
119-
Otherwise, if you're finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.
137+
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.
120138
121139
> [!IMPORTANT]
122-
> 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 on the left instead of deleting the resource group.
140+
> 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.
123141
>
124142
125-
Sign in to the [Azure portal](https://portal.azure.com) and select **Resource groups**.
143+
1. Sign in to the [Azure portal](https://portal.azure.com) and select **Resource groups**.
144+
145+
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**.
146+
147+
![Delete Azure Resource group](./media/cache-nodejs-get-started/redis-cache-delete-resource-group.png)
126148
127-
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**.
149+
1. Confirm the deletion of the resource group. Enter the name of your resource group to confirm, and select **Delete**.
128150
129-
![Delete Azure Resource group](./media/cache-nodejs-get-started/redis-cache-delete-resource-group.png)
151+
1. After a few moments, the resource group and all of its contained resources are deleted.
130152
131-
You'll be asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm, and select **Delete**.
153+
## Get the sample code
132154
133-
After a few moments, the resource group and all of its contained resources are deleted.
155+
Get the [Node.js quickstart](https://github.com/Azure-Samples/azure-cache-redis-samples/tree/main/quickstart/nodejs) on GitHub.
134156
135157
## Next steps
136158

0 commit comments

Comments
 (0)