快速入门:将 Azure Redis 缓存与 Node.js 配合使用Quickstart: Use Azure Cache for Redis with Node.js

在本快速入门中,会将 Azure Redis 缓存合并到 Node.js 应用中,以便能够访问 Azure 中的任何应用程序都可以访问的安全专用缓存。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.


有关使用其他 Node.js 客户端的示例,请参阅 Node.js Redis 客户端中所列的适用于 Node.js 客户端的各个文档。For examples of using other Node.js clients, see the individual documentation for the Node.js clients listed at Node.js Redis clients.

创建缓存Create a cache

  1. 若要创建缓存,请登录到 Azure 门户并选择“创建资源” 。To create a cache, sign in to the Azure portal and select Create a resource.


  2. 在“新建”页上选择“数据库”,然后选择“Azure Cache for Redis”。 On the New page, select Databases and then select Azure Cache for Redis.

    选择“Azure Cache for Redis”

  3. 在“新建 Redis 缓存”页上配置新缓存的设置。 On the New Redis Cache page, configure the settings for your new cache.

    设置Setting 建议的值Suggested value 说明Description
    DNS 名称DNS name 输入任何全局唯一的名称。Enter a globally unique name. 缓存名称必须是包含 1 到 63 个字符的字符串,只能包含数字、字母或连字符。The cache name must be a string between 1 and 63 characters that contains only numbers, letters, or hyphens. 该名称必须以数字或字母开头和结尾,且不能包含连续的连字符。The name must start and end with a number or letter, and can't contain consecutive hyphens. 缓存实例的主机名是 <DNS 名称>.redis.cache.chinacloudapi.cn 。 Your cache instance's host name will be <DNS name>.redis.cache.chinacloudapi.cn.
    订阅Subscription 单击下拉箭头并选择你的订阅。Drop down and select your subscription. 要在其下创建此新的 Azure Cache for Redis 实例的订阅。The subscription under which to create this new Azure Cache for 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.
    LocationLocation 单击下拉箭头并选择一个位置。Drop down and select a location. 选择与要使用该缓存的其他服务靠近的区域Select a region near other services that will use your cache.
    定价层Pricing tier 单击下拉箭头并选择一个定价层Drop down and select a Pricing tier. 定价层决定可用于缓存的大小、性能和功能。The pricing tier determines the size, performance, and features that are available for the cache. 有关详细信息,请参阅用于 Redis 的 Azure 缓存概述For more information, see Azure Cache for Redis Overview.
  4. 选择“创建” 。Select Create.

    创建 Azure Redis 缓存

    创建缓存需要花费片刻时间。It takes a while for the cache to create. 可以在 Azure Cache for Redis 的“概述”页上监视进度。 You can monitor progress on the Azure Cache for Redis Overview page. 如果“状态”显示为“正在运行”,则表示该缓存可供使用。 When Status shows as Running, the cache is ready to use.

    创建的 Azure Redis 缓存

从 Azure 门户检索主机名、端口和访问密钥Retrieve host name, ports, and access keys from the Azure portal

若要连接到某个 Azure Cache for Redis 实例,缓存客户端需要该缓存的主机名、端口和密钥。To connect to an Azure Cache for Redis instance, cache clients need the host name, ports, and a key for the cache. 在某些客户端中,这些项的名称可能略有不同。Some clients might refer to these items by slightly different names. 可以从 Azure 门户检索主机名、端口和访问密钥。You can get the host name, ports, and keys from the Azure portal.

  • 若要获取访问密钥,请在缓存的左侧导航中选择“访问密钥”。 To get the access keys, from your cache left navigation, select Access keys.

    Azure Redis 缓存密钥

  • 若要获取主机名和端口,请在缓存的左侧导航栏中选择“属性”。 To get the host name and ports, from your cache left navigation, select Properties. 主机名的格式为 <DNS 名称>.redis.cache.chinacloudapi.cn 。The host name is of the form <DNS name>.redis.cache.chinacloudapi.cn.

    Azure Redis 缓存属性

主机名访问密钥添加环境变量。Add environment variables for your HOST NAME and Primary access key. 你将通过代码使用这些变量,而不是直接在代码中包含敏感信息。You will use these variables from your code instead of including the sensitive information directly in your code.

set REDISCACHEHOSTNAME=contosoCache.redis.cache.chinacloudapi.cn

连接到缓存Connect to the cache

最新版本的 node_redis 支持使用 TLS 连接到 Azure Cache for Redis。The latest builds of node_redis provide support for connecting to Azure Cache for Redis using TLS. 以下示例演示如何使用 TLS 终结点 6380 连接到 Azure Cache for Redis。The following example shows how to connect to Azure Cache for Redis using the TLS endpoint of 6380.

var redis = require("redis");

// Add your cache name and access key.
var client = redis.createClient(6380, process.env.REDISCACHEHOSTNAME,
    {auth_pass: process.env.REDISCACHEKEY, tls: {servername: process.env.REDISCACHEHOSTNAME}});

不要为代码中的每个操作创建新连接,Don't create a new connections for each operation in your code. 而应尽可能重用连接。Instead, reuse connections as much as possible.

新建 Node.js 应用Create a new Node.js app

创建名为 redistest.js 的新脚本文件。Create a new script file named redistest.js. 使用命令 npm install redis bluebird 安装所需的包。Use the command npm install redis bluebird to install required packages.

将下面的示例 JavaScript 添加到文件。Add the following example JavaScript to the file. 此代码演示如何使用缓存主机名和密钥环境变量连接到 Azure Redis 缓存实例。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. 还执行了 PINGCLIENT LIST 命令。The PING and CLIENT LIST commands are also executed. 有关将 Redis 与 node_redis 客户端一起使用的更多示例,请参阅 https://redis.js.org/For more examples of using Redis with the node_redis client, see https://redis.js.org/.

var redis = require("redis");
var bluebird = require("bluebird");

// Convert Redis client API to use promises, to make it usable with async/await syntax

async function testCache() {

    // Connect to the Azure Cache for Redis over the TLS port using the key.
    var cacheConnection = redis.createClient(6380, process.env.REDISCACHEHOSTNAME, 
        {auth_pass: process.env.REDISCACHEKEY, tls: {servername: process.env.REDISCACHEHOSTNAME}});
    // Perform cache operations using the cache connection object...

    // Simple PING command
    console.log("\nCache command: PING");
    console.log("Cache response : " + await cacheConnection.pingAsync());

    // Simple get and put of integral data types into the cache
    console.log("\nCache command: GET Message");
    console.log("Cache response : " + await cacheConnection.getAsync("Message"));    

    console.log("\nCache command: SET Message");
    console.log("Cache response : " + await cacheConnection.setAsync("Message",
        "Hello! The cache is working from Node.js!"));    

    // Demonstrate "SET Message" executed as expected...
    console.log("\nCache command: GET Message");
    console.log("Cache response : " + await cacheConnection.getAsync("Message"));    

    // Get the client list, useful to see if connection list is growing...
    console.log("\nCache command: CLIENT LIST");
    console.log("Cache response : " + await cacheConnection.clientAsync("LIST"));    


使用 Node.js 运行该脚本。Run the script with Node.js.

node redistest.js

在下面的示例中,可以看到 Message 键以前有一个缓存值,该值是使用 Azure 门户中的 Redis 控制台设置的。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. 应用还执行了 PINGCLIENT LIST 命令。The app also executed the PING and CLIENT LIST commands.

已完成的 Redis 缓存应用

清理资源Clean up resources

如果想要继续学习下一篇教程,可以保留本快速入门中创建的资源,以便重复使用。If you will be continuing to the next tutorial, you can keep the resources created in this quickstart and reuse them.

如果已完成快速入门示例应用程序,可以删除本快速入门中创建的 Azure 资源,以免产生费用。Otherwise, if you are finished with the quickstart sample application, you can delete the Azure resources created in this quickstart to avoid charges.


删除资源组的操作不可逆,资源组以及其中的所有资源将被永久删除。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 from their respective blades instead of deleting the resource group.

登录到 Azure 门户,然后选择“资源组”。 Sign in to the Azure portal and select Resource groups.

在“按名称筛选”文本框中,输入资源组的名称 。In the Filter by name text box, enter the name of your resource group. 本文的说明使用了名为 TestResources 的资源组。The instructions for this article used a resource group named TestResources. 在结果列表中的资源组上,选择“...”,然后选择“删除资源组” 。On your resource group in the result list, select ... then Delete resource group.

删除 Azure 资源组

系统会要求确认是否删除资源组。You will be asked to confirm the deletion of the resource group. 重新键入资源组的名称进行确认,然后选择“删除” 。Enter the name of your resource group to confirm, and select Delete.

片刻之后,将会删除该资源组及其包含的所有资源。After a few moments, the resource group and all of its contained resources are deleted.

后续步骤Next steps

本快速入门介绍了如何通过 Node.js 应用程序使用 Azure Redis 缓存。In this quickstart, you learned how to use Azure Cache for Redis from a Node.js application. 请继续学习下一个快速入门,将 Azure Redis 缓存与 ASP.NET Web 应用配合使用。Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.