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

在本快速入門中,您會將 Azure Cache for Redis 納入 .NET Core 應用程式中,以便存取可從 Azure 內的任何應用程式存取的安全專用快取。In this quickstart, you incorporate Azure Cache for Redis into a .NET Core app to have access to a secure, dedicated cache that is accessible from any application within Azure. 您會在 .NET Core 主控台應用程式中明確地搭配使用 StackExchange.Redis 用戶端與 C# 程式碼。You specifically use the StackExchange.Redis client with C# code in a .NET Core console app.

PrerequisitesPrerequisites

建立快取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 快取屬性

請記下 主機名稱主要 存取金鑰。Make a note of the HOST NAME and the Primary access key. 您後續將會使用這些值來建構 CacheConnection 密碼。You will use these values later to construct the CacheConnection secret.

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

在新的命令視窗中執行下列命令,以建立新的 .NET Core 主控台應用程式:Open a new command window and execute the following command to create a new .NET Core console app:

dotnet new console -o Redistest

在命令視窗中,切換至新的 Redistest 專案目錄。In your command window, change to the new Redistest project directory.

將祕密管理員新增至專案Add Secret Manager to the project

在本節中,您會將祕密管理員工具 (機器翻譯) 新增至您的專案。In this section, you will add the Secret Manager tool to your project. 祕密管理員工具能儲存專案樹狀結構外開發工作的敏感性資料。The Secret Manager tool stores sensitive data for development work outside of your project tree. 此作法能協助避免於原始程式碼內意外共用應用程式祕密。This approach helps prevent the accidental sharing of app secrets within source code.

開啟您的 Redistest.csproj 檔案。Open your Redistest.csproj file. 新增 DotNetCliToolReference 元素以包含 Microsoft.Extensions.SecretManager.ToolsAdd a DotNetCliToolReference element to include Microsoft.Extensions.SecretManager.Tools. 同時也新增 UserSecretsId 元素 (如下所示),然後儲存檔案。Also add a UserSecretsId element as shown below, and save the file.

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.0</TargetFramework>
        <UserSecretsId>Redistest</UserSecretsId>
    </PropertyGroup>
    <ItemGroup>
        <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
    </ItemGroup>
</Project>

執行下列命令,將 Microsoft.Extensions.Configuration.UserSecrets 套件新增至專案:Execute the following command to add the Microsoft.Extensions.Configuration.UserSecrets package to the project:

dotnet add package Microsoft.Extensions.Configuration.UserSecrets

執行下列命令以還原您的套件:Execute the following command to restore your packages:

dotnet restore

在命令視窗中,在取代您的快取名稱和主要存取金鑰的預留位置 (包括角括號) 後,執行下列命令以儲存名為 CacheConnection 的新密碼:In your command window, execute the following command to store a new secret named CacheConnection, after replacing the placeholders (including angle brackets) for your cache name and primary access key:

dotnet user-secrets set CacheConnection "<cache name>.redis.cache.windows.net,abortConnect=false,ssl=true,password=<primary-access-key>"

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

using Microsoft.Extensions.Configuration;

將下列成員新增至 Program.cs 中的 Program 類別。Add the following members to the Program class in Program.cs. 此程式碼會將針對 Azure Cache for Redis 連接字串存取使用者祕密的設定初始化。This code initializes a configuration to access the user secret for the Azure Cache for Redis connection string.

private static IConfigurationRoot Configuration { get; set; }
const string SecretName = "CacheConnection";

private static void InitializeConfiguration()
{
    var builder = new ConfigurationBuilder()
        .AddUserSecrets<Program>();

    Configuration = builder.Build();
}

設定快取用戶端Configure the cache client

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

在命令視窗中,在 Redistest 專案目錄中執行下列命令:In your command window, execute the following command in the Redistest project directory:

dotnet add 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

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

using StackExchange.Redis;

與 Azure Cache for Redis 的連線會由 ConnectionMultiplexer 類別所管理。The connection to the Azure Cache for Redis 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.

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 = Configuration[SecretName];
    return ConnectionMultiplexer.Connect(cacheConnection);
});

public static ConnectionMultiplexer Connection
{
    get
    {
        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 Cache for Redis 的連線,呼叫也會成功。abortConnect is set to false, which means that the call succeeds even if a connection to the Azure Cache for Redis 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 密碼的值可使用密碼管理員組態提供者來存取,並作為密碼參數。The value of the CacheConnection secret is accessed using the Secret Manager configuration provider and used as the password parameter.

執行快取命令Executing cache commands

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

static void Main(string[] args)
{
    InitializeConfiguration();

    // 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 Core console app!\"";
    Console.WriteLine("\nCache command  : " + cacheCommand + " or StringSet()");
    Console.WriteLine("Cache response : " + cache.StringSet("Message", "Hello! The cache is working from a .NET Core console app!").ToString());

    // Demonstrate "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="));

    lazyConnection.Value.Dispose();
}

儲存 Program.csSave Program.cs.

Azure Cache for Redis 具有可用來以邏輯方式區隔 Azure Cache for Redis 內資料的可設定資料庫數目 (預設值為 16 個)。Azure Cache for Redis has a configurable number of databases (default of 16) that can be used to logically separate the data within an Azure Cache for Redis. 該程式碼會連線至預設資料庫 (DB 0)。The code connects to the default database, 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.

在命令視窗中執行下列命令,以建置應用程式:Execute the following command in your command window to build the app:

dotnet build

然後,使用下列命令執行應用程式:Then run the app with the following command:

dotnet run

在下列範例中,您會看到 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 Cache for Redis 可以快取 .NET 物件及基本資料類型,但必須先將 .NET 物件序列化,才能加以快取。Azure Cache for Redis 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.

執行下列命令,將 Newtonsoft.json 套件新增至應用程式:Execute the following command to add the Newtonsoft.json package to the app:

dotnet add 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");

儲存 Program.cs,並使用下列命令重建應用程式:Save Program.cs and rebuild the app with the following command:

dotnet build

使用下列命令執行應用程式,以測試 .NET 物件的序列化:Run the app with the following command to test serialization of .NET objects:

dotnet run

主控台應用程式已完成

清除資源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 Core 應用程式使用 Azure Cache for Redis。In this quickstart, you learned how to use Azure Cache for Redis from a .NET Core 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.

想要最佳化並節省您的雲端費用嗎?Want to optimize and save on your cloud spending?