快速入門:搭配使用 Azure Redis 快取與 .NET 應用程式Quickstart: Use Azure Redis Cache with a .NET application

本快速入門說明如何開始搭配使用 Microsoft Azure Redis 快取與 .NET。This quickstart shows you how to get started using Microsoft Azure Redis Cache with .NET. Microsoft Azure Redis 快取以廣受使用的開放原始碼 Redis 快取為基礎。Microsoft Azure Redis Cache is based on the popular open-source Redis Cache. 它可讓您存取由 Microsoft 管理的安全、專用 Redis 快取。It gives you access to a secure, dedicated Redis cache, managed by Microsoft. 使用 Azure Redis 快取建立的快取,可透過 Microsoft Azure 內的任何應用程式加以存取。A cache created using Azure Redis Cache is accessible from any application within Microsoft Azure.

在這個快速入門中,您會在主控台應用程式中搭配使用 StackExchange.Redis 用戶端與 C# 程式碼。In this quickstart, you will use the StackExchange.Redis client with C# code in a console app. 您會建立快取,並設定 .NET 用戶端應用程式。You will create a cache and configure the .NET client app. 然後,您會在快取中新增並更新物件。Then, you will add, and update objects in the cache.


如果您沒有 Azure 訂用帳戶,請在開始前建立 免費帳戶If you don't have an Azure subscription, create a free account before you begin.


建立快取Create a cache

  1. 若要建立快取,請先登入 Azure 入口網站To create a cache, first sign in to the Azure portal. 然後選取 [建立資源] > [資料庫] > [Redis 快取]。Then select Create a resource > Databases > Redis Cache.

    New cache

  2. 在 [新的 Redis 快取] 中,配置新快取的設定。In New Redis Cache, configure the settings for your new cache.

    設定Setting 建議的值Suggested value 說明Description
    DNS 名稱DNS name 全域唯一的名稱Globally unique name 快取名稱。The cache name. 該名稱必須是介於 1 到 63 個字元的字串,而且只能包含數字、字母和 - 字元。It must be a string between 1 and 63 characters and contain only numbers, letters, and the - character. 快取名稱的開頭或結尾不能是 - 字元,且連續的 - 字元無效。The cache name cannot start or end with the - character, and consecutive - characters are not valid.
    訂用帳戶Subscription 您的訂用帳戶Your subscription 該新建立的 Azure Redis 快取執行個體所在的訂用帳戶。The subscription under which this new Azure Redis Cache instance is created.
    資源群組Resource group TestResourcesTestResources 容納新建立快取的新資源群組名稱。Name for the new resource group in which to create your cache. 將應用程式的所有資源放在群組中,藉此同時管理。By putting all the resources for an app in a group, you can manage them together. 例如,刪除資源群組會刪除所有與應用程式相關聯的資源。For example, deleting the resource group deletes all resources that are associated with the app.
    位置Location 美國東部East US 選擇其他將使用快取之服務的鄰近區域Choose a region near to other services that will use your cache.
    定價層Pricing tier 基本 C0 (250 MB 快取)Basic C0 (250 MB Cache) 快取的可用大小、效能和功能取決於定價層。The pricing tier determines the size, performance, and features that are available for the cache. 如需詳細資訊,請參閱 Azure Redis 快取概觀For more information, see Azure Redis Cache Overview.
    釘選到儀表板Pin to dashboard 已選取Selected 將新快取釘選到儀表板,以便尋找。Pin the new cache to your dashboard to make it easy to find.

    Create cache

  3. 配置新快取設定之後,請選取 [建立]。After the new cache settings are configured, select Create.

    建立快取可能需要數分鐘的時間。It can take a few minutes for the cache to be created. 若要檢查狀態,您可以監視儀表板上的進度。To check the status, you can monitor the progress on the dashboard. 建立快取之後,其顯示的狀態為 [執行中],而且已經可供使用。After the cache has been created, it shows the status Running, and is ready for use.

    Cache created

使用 Azure 入口網站來擷取主機名稱、連接埠及存取金鑰Retrieve host name, ports, and access keys by using the Azure portal

在連接 Azure Redis 快取執行個體時,快取用戶端需要主機名稱、連接埠和快取金鑰。When connecting to an Azure Redis Cache 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 retrieve this information in the Azure portal.

擷取存取金鑰和主機名稱To retrieve the access keys and host name

  1. 若要使用 Azure 入口網站來擷取存取金鑰,請瀏覽至快取並選取 [存取金鑰]。To retrieve the access keys by using the Azure portal, browse to your cache and select Access keys.

    Azure Redis 快取金鑰

  2. 若要擷取主機名稱和連接埠,請選取 [屬性]。To retrieve the host name and ports, select Properties.

    Azure Redis 快取屬性

在電腦上建立名為 CacheSecrets.config 的檔案,並將它放在應用程式範例的原始程式碼不會簽入的位置。Create a file on your computer named CacheSecrets.config and place it in a location where it won't be checked in with the source code of your sample application. 在本快速入門中,CacheSecrets.config 檔案位於這裡 (C:\AppSecrets\CacheSecrets.config)。For this quickstart, the CacheSecrets.config file is located here, C:\AppSecrets\CacheSecrets.config.

編輯 CacheSecrets.config 檔案,並新增下列內容:Edit the CacheSecrets.config file and add the following contents:

    <add key="CacheConnection" value="<cache-name>.redis.cache.windows.net,abortConnect=false,ssl=true,password=<access-key>"/>

<cache-name> 取代為快取主機名稱。Replace <cache-name> with your cache host name.

<access-key> 取代為快取的主要金鑰。Replace <access-key> with the primary key for your cache.

建立主控台應用程式Create a console app

在 Visual Studio 中,按一下 [檔案] > [新增] > [專案]。In Visual Studio, click File > New > Project.

Visual C# 下,按一下 [Windows 傳統桌面],然後按一下 [主控台應用程式] 和 [確定],以建立新的主控台應用程式。Under Visual C#, click Windows Classic Desktop and then click Console App, and OK to create a new console application.

設定快取用戶端Configure the cache client

在本節中,您會設定主控台應用程式,以使用適用於 .NET 的 StackExchange.Redis 用戶端。In this section, you will configure the console application to use the StackExchange.Redis client for .NET.

在 Visual Studio 中,按一下 [工具] > [NuGet 套件管理員] > [Package Manager Console],然後從 Package Manager Console 視窗執行下列命令。In Visual Studio, click Tools > NuGet Package Manager > Package Manager Console, and run the following command from the Package Manager Console window.

Install-Package StackExchange.Redis

安裝完成後,StackExchange.Redis 快取用戶端即可與專案搭配使用。Once the installation is completed, the StackExchange.Redis cache client is available to use with your project.

連接到快取Connect to the cache

在 Visual Studio 中開啟 App.config 檔案,並將其更新為包含 appSettings file 屬性 (會參考 CacheSecrets.config 檔案)。In Visual Studio, open your App.config file and update it to include an appSettings file attribute that references the CacheSecrets.config file.

<?xml version="1.0" encoding="utf-8" ?>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />

    <appSettings file="C:\AppSecrets\CacheSecrets.config"></appSettings>  


在 [方案總管] 中,以滑鼠右鍵按一下 [參考],然後按一下 [新增參考]。In Solution Explorer, right-click References and click Add a reference. 新增 System.Configuration 組件的參考。Add a reference to the System.Configuration assembly.

將下列 using 陳述式新增至 Program.cs:Add the following using statements to Program.cs:

using StackExchange.Redis;
using System.Configuration;

與 Azure Redis 快取的連線是由 ConnectionMultiplexer 類別所管理。The connection to the Azure Redis Cache is managed by the ConnectionMultiplexer class. 整個用戶端應用程式中都應該共用和重複使用此類別。This class should be shared and reused throughout your client application. 請勿對每個作業建立新連線。Do not create a new connection for each operation.

請勿將認證儲存在原始程式碼中。Never store credentials in source code. 為了簡化這個範例,我只使用外部密碼組態檔。To keep this sample simple, I’m only using an external secrets config file. 搭配使用 Azure 金鑰保存庫與憑證會更好。A better approach would be to use Azure Key Vault with certificates.

在 Program.cs 中,對主控台應用程式的 Program 類別新增下列成員:In Program.cs, add the following members to the Program class of your console application:

        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
            string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();
            return ConnectionMultiplexer.Connect(cacheConnection);

        public static ConnectionMultiplexer Connection
                return lazyConnection.Value;

這個在應用程式中共用 ConnectionMultiplexer 執行個體的方法,會使用可傳回已連線執行個體的靜態屬性。This approach to sharing a ConnectionMultiplexer instance in your application uses a static property that returns a connected instance. 此程式碼會提供安全執行緒方式,只初始化一個已連線的 ConnectionMultiplexer 執行個體。The code provides a thread-safe way to initialize only a single connected ConnectionMultiplexer instance. abortConnect 會設為 false,這表示即使無法建立與 Azure Redis 快取的連線,呼叫也會成功。abortConnect is set to false, which means that the call succeeds even if a connection to the Azure Redis Cache is not established. ConnectionMultiplexer 的主要功能之一,就是一旦網路問題或其他原因獲得解決,它就會自動恢復與快取的連接。One key feature of ConnectionMultiplexer is that it automatically restores connectivity to the cache once the network issue or other causes are resolved.

CacheConnection appSetting 的值可用來從 Azure 入口網站中將快取連接字串參考作為密碼參數。The value of the CacheConnection appSetting is used to reference the cache connection string from the Azure portal as the password parameter.

執行快取命令Executing cache commands

對主控台應用程式 Program 類別的 Main 程序新增下列程式碼:Add the following code for the Main procedure of the Program class for your console application:

        static void Main(string[] args)
            // Connection refers to a property that returns a ConnectionMultiplexer
            // as shown in the previous example.
            IDatabase cache = lazyConnection.Value.GetDatabase();

            // Perform cache operations using the cache object...

            // Simple PING command
            string cacheCommand = "PING";
            Console.WriteLine("\nCache command  : " + cacheCommand);
            Console.WriteLine("Cache response : " + cache.Execute(cacheCommand).ToString());

            // Simple get and put of integral data types into the cache
            cacheCommand = "GET Message";
            Console.WriteLine("\nCache command  : " + cacheCommand + " or StringGet()");
            Console.WriteLine("Cache response : " + cache.StringGet("Message").ToString());

            cacheCommand = "SET Message \"Hello! The cache is working from a .NET console app!\"";
            Console.WriteLine("\nCache command  : " + cacheCommand + " or StringSet()");
            Console.WriteLine("Cache response : " + cache.StringSet("Message", "Hello! The cache is working from a .NET console app!").ToString());

            // Demostrate "SET Message" executed as expected...
            cacheCommand = "GET Message";
            Console.WriteLine("\nCache command  : " + cacheCommand + " or StringGet()");
            Console.WriteLine("Cache response : " + cache.StringGet("Message").ToString());

            // Get the client list, useful to see if connection list is growing...
            cacheCommand = "CLIENT LIST";
            Console.WriteLine("\nCache command  : " + cacheCommand);
            Console.WriteLine("Cache response : \n" + cache.Execute("CLIENT", "LIST").ToString().Replace("id=", "id="));


Azure Redis 快取具有可供用來以邏輯方式區隔 Redis 快取內資料的可設定數目資料庫 (預設值為 16 個)。 該程式碼會連線至預設資料庫 (DB 0)。 如需詳細資訊,請參閱 Redis 資料庫是什麼?預設 Redis 伺服器組態For more information, see What are Redis databases? and Default Redis server configuration.

您可以使用 StringSetStringGet 方法來儲存和擷取快取項目。Cache items can be stored and retrieved by using the StringSet and StringGet methods.

Redis 會將多數資料儲存為 Redis 字串,但這些字串可能包含許多類型的資料,包括序列化的二進位資料 (在快取中儲存 .NET 物件時可能會用到)。Redis stores most data as Redis strings, but these strings can contain many types of data, including serialized binary data, which can be used when storing .NET objects in the cache.

Ctrl+F5 以建置並執行主控台應用程式。Press Ctrl+F5 to build and run the console app.

在下列範例中,您會看到 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.


使用快取中的 .NET 物件Work with .NET objects in the cache

Azure Redis 快取可以快取 .NET 物件及基本資料類型,但必須先將 .NET 物件序列化,才能加以快取。Azure Redis Cache can cache both .NET objects and primitive data types, but before a .NET object can be cached it must be serialized. .NET 物件序列化是應用程式開發人員的責任,同時賦與開發人員選擇序列化程式的彈性。This .NET object serialization is the responsibility of the application developer, and gives the developer flexibility in the choice of the serializer.

將物件序列化的其中一個簡單方法就是使用 Newtonsoft.Json 中的 JsonConvert 序列化方法並進行 JSON 的雙向序列化。One simple way to serialize objects is to use the JsonConvert serialization methods in Newtonsoft.Json and serialize to and from JSON. 在本節中,您會對快取新增 .NET 物件。In this section, you will add a .NET object to the cache.

在 Visual Studio 中,按一下 [工具] > [NuGet 套件管理員] > [Package Manager Console],然後從 Package Manager Console 視窗執行下列命令。In Visual Studio, click Tools > NuGet Package Manager > Package Manager Console, and run the following command from the Package Manager Console window.

Install-Package Newtonsoft.Json

在 Program.cs 開頭處新增以下 using 陳述式:Add the following using statement to the top of Program.cs:

using Newtonsoft.Json;

將下列 Employee 類別定義新增至 Program.cs:Add the following Employee class definition to Program.cs:

        class Employee
            public string Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }

            public Employee(string EmployeeId, string Name, int Age)
                this.Id = EmployeeId;
                this.Name = Name;
                this.Age = Age;

在 Program.cs 中的 Main() 程序底部,於 Dispose() 呼叫之前,對快取新增下列程式碼,並擷取已序列化的 .NET 物件:At the bottom of Main() procedure in Program.cs, and before the call to Dispose(), add the following lines of code to cache and retrieve a serialized .NET object:

            // Store .NET object to cache
            Employee e007 = new Employee("007", "Davide Columbo", 100);
            Console.WriteLine("Cache response from storing Employee .NET object : " + 
                cache.StringSet("e007", JsonConvert.SerializeObject(e007)));

            // Retrieve .NET object from cache
            Employee e007FromCache = JsonConvert.DeserializeObject<Employee>(cache.StringGet("e007"));
            Console.WriteLine("Deserialized Employee .NET object :\n");
            Console.WriteLine("\tEmployee.Name : " + e007FromCache.Name);
            Console.WriteLine("\tEmployee.Id   : " + e007FromCache.Id);
            Console.WriteLine("\tEmployee.Age  : " + e007FromCache.Age + "\n");

Ctrl+F5 以建置並執行主控台應用程式,來測試 .NET 物件的序列化。Press Ctrl+F5 to build and run the console app to test serialization of .NET objects.


清除資源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 click Resource groups.

在 [依名稱篩選...] 文字方塊中,輸入您的資源群組名稱。In the Filter by name... textbox, type 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, click ... then Delete resource group.


系統將會要求您確認是否刪除資源。You will be asked to confirm the deletion of the resource group. 輸入您的資源群組名稱來確認,然後按一下 [刪除]。Type the name of your resource group to confirm, and click Delete.

片刻過後,系統便會刪除該資源群組及其所有內含的資源。After a few moments, the resource group and all of its contained resources are deleted.

後續步驟Next steps

在本快速入門中,您已了解如何從 .NET 應用程式使用 Azure Redis 快取。In this quickstart, you learned how to use Azure Redis Cache from a .NET application. 請繼續閱讀下一個快速入門,來搭配使用 Redis 快取與 ASP.NET Web 應用程式。Continue to the next quickstart to use Redis Cache with an ASP.NET web app.