快速入門:在 Node.js 中使用 Azure Cache for RedisQuickstart: Use Azure Cache for Redis in Node.js

在本快速入門中,您會將 Azure Cache for 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.

PrerequisitesPrerequisites

如需使用其他 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 name>.redis.cache.windows.netYour cache instance's host name will be <DNS name>.redis.cache.windows.net.
    訂用帳戶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.
    位置Location 下拉並選取位置。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. 如需詳細資訊,請參閱 Azure Cache for Redis 概觀For more information, see Azure Cache for Redis Overview.
  4. 選取 [網路] 索引標籤,或按一下頁面底部的 [網路] 按鈕。Select the Networking tab or click the Networking button at the bottom of the page.

  5. 在 [網路功能] 索引標籤中,選取您的連線方法。In the Networking tab, select your connectivity method.

  6. 選取頁面底部的 [下一步:進階] 索引標籤,或按一下頁面底部的 [下一步:進階] 按鈕。Select the Next: Advanced tab or click the Next: Advanced button on the bottom of the page.

  7. 在基本或標準快取執行個體的 [進階] 索引標籤中,如果您想要啟用非 TLS 連接埠,請選取啟用切換。In the Advanced tab for a basic or standard cache instance, select the enable toggle if you want to enable a non-TLS port. 您也可以選擇要使用 Redis 版本 4 或 (預覽) 6。You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

    Redis 版本 4 或 6。

  8. 在高階快取執行個體的 [進階] 索引標籤中,設定非 TLS 連接埠、叢集和資料持續性的設定。In the Advanced tab for premium cache instance, configure the settings for non-TLS port, clustering, and data persistence. 您也可以選擇要使用 Redis 版本 4 或 (預覽) 6。You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

  9. 選取頁面底部的 [下一步:標記] 索引標籤,或按一下頁面底部的 [下一步:標記] 按鈕。Select the Next: Tags tab or click the Next: Tags button at the bottom of the page.

  10. 在 [標記] 索引標籤中,如果您想要分類資源,可以選擇性地輸入名稱和值。Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.

  11. 選取 [檢閱 + 建立]。Select Review + create. 您會移至 [檢閱 + 建立] 索引標籤,其中 Azure 會驗證您的組態。You're taken to the Review + create tab where Azure validates your configuration.

  12. 出現綠色的「通過驗證」訊息之後,請選取 [建立]。After the green Validation passed message appears, select Create.

建立快取需要一些時間。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 入口網站擷取主機名稱、連接埠和存取金鑰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 Cache for Redis 金鑰

  • 若要取得主機名稱和連接埠,請從快取的左側導覽中選取 [屬性] 。To get the host name and ports, from your cache left navigation, select Properties. 主機名稱的格式為 <DNS name>.redis.cache.windows.netThe host name is of the form <DNS name>.redis.cache.windows.net.

    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.windows.net
set REDISCACHEKEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

連接到快取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. 下列範例示範如何使用 6380 的 TLS 端點來連線到 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 connection 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 Cache for 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
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

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"));    
}

testCache();

使用 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 Cache 應用程式已完成

清除資源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 Cache for Redis。In this quickstart, you learned how to use Azure Cache for Redis from a Node.js application. 請繼續閱讀下一個快速入門,以搭配使用 Azure Cache for Redis 與 ASP.NET Web 應用程式。Continue to the next quickstart to use Azure Cache for Redis with an ASP.NET web app.