如何使用 Azure Redis 快取How to Use Azure Redis Cache

本指南示範如何開始使用 Azure Redis 快取This guide shows you how to get started using Azure Redis Cache. 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.

Microsoft Azure Redis 快取有下列階層:Microsoft Azure Redis Cache is available in the following tiers:

  • 基本 - 單一節點。Basic – Single node. 多種大小,最高為 53 GB。Multiple sizes up to 53 GB.
  • 標準 – 兩個節點 (主要/從屬)。Standard – Two-node Primary/Replica. 多種大小,最高為 53 GB。Multiple sizes up to 53 GB. 99.9% SLA。99.9% SLA.
  • 進階 – 兩個節點的主要/從屬,最多具有 10 個分區。Premium – Two-node Primary/Replica with up to 10 shards. 提供多種大小,範圍從 6 GB 到 530 GB。Multiple sizes from 6 GB to 530 GB. 所有「標準」層級的功能以及更多功能,可支援 Redis 叢集Redis 持續性Azure 虛擬網路All Standard tier features and more including support for Redis cluster, Redis persistence, and Azure Virtual Network. 99.9% SLA。99.9% SLA.

每一個階層都有不同的功能和價格。Each tier differs in terms of features and pricing. 如需價格的相關資訊,請參閱 快取價格詳細資料For information on pricing, see Cache Pricing Details.

本指南說明如何使用採用 C# 程式碼的 StackExchange.Redis 用戶端。This guide shows you how to use the StackExchange.Redis client using C# code. 涵蓋的案例包括建立和設定快取設定快取用戶端,以及新增和移除快取中的物件The scenarios covered include creating and configuring a cache, configuring cache clients, and adding and removing objects from the cache. 如需使用 Azure Redis 快取的詳細資訊,請參閱 後續步驟For more information on using Azure Redis Cache, see Next Steps. 如需使用 Redis 快取建置 ASP.NET MVC Web 應用程式的逐步教學課程,請參閱 如何使用 Redis 快取建立 Web 應用程式For a step-by-step tutorial of building an ASP.NET MVC web app with Redis Cache, see How to create a Web App with Redis Cache.

開始使用 Azure Redis 快取Get Started with Azure Redis Cache

開始使用 Azure Redis 快取相當簡單。Getting started with Azure Redis Cache is easy. 若要開始,請佈建並設定快取。To get started, you provision and configure a cache. 接著,設定快取用戶端,以便它們可以存取快取。Next, you configure the cache clients so they can access the cache. 一旦設定了快取用戶端,就可以開始使用它們。Once the cache clients are configured, you can begin working with them.

建立快取Create a cache

若要建立快取,請先登入 Azure 入口網站,然後按一下 [新增] > [資料庫] > [Redis 快取]。To create a cache, first sign in to the Azure portal, and click New > Databases > Redis Cache.

注意

如果您沒有 Azure 帳戶,只需要幾分鐘的時間就可以 免費申請 Azure 帳戶If you don't have an Azure account, you can Open an Azure account for free in just a couple of minutes.

New cache

注意

除了在 Azure 入口網站中建立快取,您也可以使用 Resource Manager 範本、PowerShell 或 Azure CLI 來建立。In addition to creating caches in the Azure portal, you can also create them using Resource Manager templates, PowerShell, or Azure CLI.

在 [新增 Redis 快取] 分頁中,指定所需的快取組態。In the New Redis Cache blade, specify the desired configuration for the cache.

Create cache

  • 在 [DNS 名稱] 中,輸入要用於快取端點的唯一快取名稱。In Dns name, enter a unique cache name to use for the cache endpoint. 快取名稱必須是介於 1 到 63 個字元的字串,而且只能包含數字、字母和 - 字元。The cache name 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.
  • 針對 [訂用帳戶] ,選取您要用於快取的 Azure 訂用帳戶。For Subscription, select the Azure subscription that you want to use for the cache. 如果您的帳戶僅有一個訂用帳戶,則會自動加以選取,而且不會顯示 [訂用帳戶] 下拉式清單。If your account has only one subscription, it will be automatically selected and the Subscription drop-down will not be displayed.
  • 在 [資源群組] 中,選取或建立快取的資源群組。In Resource group, select or create a resource group for your cache. 如需詳細資訊,請參閱使用資源群組管理您的 Azure 資源For more information, see Using Resource groups to manage your Azure resources.
  • 使用 [位置] 來指定管理快取所在的地理位置。Use Location to specify the geographic location in which your cache is hosted. 為獲得最佳效能,Microsoft 強烈建議您在與快取用戶端應用程式相同的區域中建立快取。For the best performance, Microsoft strongly recommends that you create the cache in the same region as the cache client application.
  • 使用 [價格層] 來選取需要的快取大小和功能。Use Pricing tier to select the desired cache size and features.
  • Redis 叢集 可讓您建立大於 53 GB 的快取,以及將資料分散於多個 Redis 節點。Redis cluster allows you to create caches larger than 53 GB and to shard data across multiple Redis nodes. 如需詳細資訊,請參閱 如何設定進階 Azure Redis 快取的叢集For more information, see How to configure clustering for a Premium Azure Redis Cache.
  • Redis 持續性 可讓您將您的快取保存至 Azure 儲存體帳戶。Redis persistence offers the ability to persist your cache to an Azure Storage account. 如需設定永續性的相關指示,請參閱 如何設定進階 Azure Redis Cache 的永續性For instructions on configuring persistence, see How to configure persistence for a Premium Azure Redis Cache.
  • 虛擬網路 藉由將您的快取存取權限制於指定的 Azure 虛擬網路內的用戶端,以提供增強的安全性和隔離。Virtual Network provides enhanced security and isolation by restricting access to your cache to only those clients within the specified Azure Virtual Network. 您可以使用 VNet 的所有功能,例如子網路、存取控制原則和其他功能,進一步限制對 Redis 的存取權。You can use all the features of VNet such as subnets, access control policies, and other features to further restrict access to Redis. 如需詳細資訊,請參閱 如何設定進階 Azure Redis 快取的虛擬網路支援For more information, see How to configure Virtual Network support for a Premium Azure Redis Cache.
  • 根據預設,新的快取會停用非 SSL 存取。By default, non-SSL access is disabled for new caches. 若要啟用非 SSL 連接埠,請核取 [解除封鎖連接埠 6379 (未以 SSL 加密)]。To enable the non-SSL port, check Unblock port 6379 (not SSL encrypted).

設定了新的快取選項之後,請按一下 [建立新快取]。Once the new cache options are configured, click Create. 建立快取可能需要數分鐘的時間。It can take a few minutes for the cache to be created. 若要檢查狀態,您可以監視開始面板上的進度。To check the status, you can monitor the progress on the startboard. 建立了快取之後,新快取的狀態會是執行中,而且準備好與預設設定搭配使用。After the cache has been created, your new cache has a Running status and is ready for use with default settings.

Cache created

在建立好之後存取快取To access your cache after it's created

您可在 Azure 入口網站中使用 [瀏覽] 刀鋒視窗來存取快取。Caches can be accessed in the Azure portal using the Browse blade.

Azure Redis 快取瀏覽刀鋒視窗

若要檢視您的快取,請按一下 [更多服務] > [Redis 快取]。To view your caches, click More services > Redis Caches. 如果您最近曾瀏覽至 [Redis 快取],您就可以直接從清單中按一下 [Redis 快取],而不需按一下 [更多服務]。If you have recently browsed to a Redis Cache, you can click Redis Caches directly from the list without clicking More services.

選取所需的快取,以檢視和設定該快取的設定。Select the desired cache to view and configure the settings for that cache.

Azure Redis 快取瀏覽快取清單

您可以從 [Redis 快取] 刀鋒視窗檢視和設定快取。You can view and configure your cache from the Redis Cache blade.

Redis 快取所有設定

如需設定快取的詳細資訊,請參閱 如何設定 Azure Redis 快取For more information about configuring your cache, see How to configure Azure Redis Cache.

設定快取用戶端Configure the cache clients

.NET 應用程式可以使用 StackExchange.Redis 快取用戶端,該用戶端可在 Visual Studio 中使用能簡化快取用戶端應用程式組態的 NuGet 套件來加以設定。.NET applications can use the StackExchange.Redis cache client, which can be configured in Visual Studio using a NuGet package that simplifies the configuration of cache client applications.

注意

如需詳細資訊,請參閱 StackExchange.Redis github 頁面和 StackExchange.Redis 快取用戶端文件For more information, see the StackExchange.Redis github page and the StackExchange.Redis cache client documentation.

若要在 Visual Studio 中使用 StackExchange.Redis NuGet 套件來設定用戶端應用程式,請在 [方案總管] 中的專案上按一下滑鼠右鍵,然後選擇 [管理 NuGet 套件]。To configure a client application in Visual Studio using the StackExchange.Redis NuGet package, right-click the project in Solution Explorer and choose Manage NuGet Packages.

Manage NuGet packages

在搜尋文字方塊中輸入 StackExchange.RedisStackExchange.Redis.StrongName、從結果選取需要的版本,然後按一下 [安裝]。Type StackExchange.Redis or StackExchange.Redis.StrongName into the search text box, select the desired version from the results, and click Install.

注意

如果您偏好使用強式名稱版本的 StackExchange.Redis 用戶端程式庫,請選取 StackExchange.Redis.StrongName;否則選取 StackExchange.RedisIf you prefer to use a strong-named version of the StackExchange.Redis client library, choose StackExchange.Redis.StrongName; otherwise choose StackExchange.Redis.

StackExchange.Redis NuGet package

NuGet 套件會為您的用戶端應用程式下載並新增必要的組件參考,以利用 StackExchange.Redis 快取用戶端來存取 Azure Redis 快取。The NuGet package downloads and adds the required assembly references for your client application to access Azure Redis Cache with the StackExchange.Redis cache client.

注意

如果您先前已經設定專案以使用 StackExchange.Redis,您就可以從 NuGet 套件管理員檢查套件更新。If you have previously configured your project to use StackExchange.Redis, you can check for updates to the package from the NuGet Package Manager. 若要檢查及安裝 StackExchange.Redis NuGet 套件的已更新版本,請按一下 [NuGet 套件管理員] 視窗中的 [更新]。To check for and install updated versions of the StackExchange.Redis NuGet package, click Updates in the the NuGet Package Manager window. 如果 StackExchange.Redis NuGet 套件有更新可用,您可以更新您的專案來使用已更新版本。If an update to the StackExchange.Redis NuGet package is available, you can update your project to use the updated version.

從 [工具] 功能表按一下 [NuGet 套用管理員]、[套件管理員主控台],然後從 [Package Manager Console] 視窗執行下列命令,也可以安裝 StackExchange.Redis NuGet 套件。You can also install the StackExchange.Redis NuGet package by clicking NuGet Package Manager, Package Manager Console from the Tools menu, and running the following command from the Package Manager Console window.

Install-Package StackExchange.Redis

一旦設定用戶端專案的快取功能,您就可以使用下列幾節中描述的技術來使用快取。Once your client project is configured for caching, you can use the techniques described in the following sections for working with your cache.

使用快取Working with Caches

本節中的步驟描述如何利用快取執行常見工作。The steps in this section describe how to perform common tasks with Cache.

連接到快取Connect to the cache

若要以程式設計方式使用快取,您需要快取的參考。To programmatically work with a cache, you need a reference to the cache. 將下面這一行加入至您想要從中使用 StackExchange.Redis 用戶端來存取 Azure Redis 快取之檔案的頂端。Add the following to the top of any file from which you want to use the StackExchange.Redis client to access an Azure Redis Cache.

using StackExchange.Redis;

注意

StackExchange.Redis 用戶端需要 .NET Framework 4 或更高版本。

與 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, and does not need to be created on a per operation basis.

若要連線至 Azure Redis 快取,並傳回已連線 ConnectionMultiplexer 的執行個體,請呼叫靜態 Connect 方法,並傳入快取端點和金鑰。To connect to an Azure Redis Cache and be returned an instance of a connected ConnectionMultiplexer, call the static Connect method and pass in the cache endpoint and key. 使用從 Azure 入口網站產生的金鑰做為密碼參數。Use the key generated from the Azure portal as the password parameter.

ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");

重要

警告:請勿將認證儲存在原始程式碼中。 為了讓這個範例簡單明瞭,我會以原始程式碼來呈現認證內容。 如需如何儲存認證的相關資訊,請參閱應用程式字串與連接字串的運作方式

如果您不想使用 SSL,請設定 ssl=false 或省略 ssl 參數。If you don't want to use SSL, either set ssl=false or omit the ssl parameter.

注意

預設會為新快取停用非 SSL 連接埠。 如需啟用非 SSL 連接埠的指示,請參閱存取連接埠

在您的應用程式中共用 ConnectionMultiplexer 執行個體的其中一種方法,就是擁有可傳回已連接執行個體的靜態屬性,類似下列範例。One approach to sharing a ConnectionMultiplexer instance in your application is to have a static property that returns a connected instance, similar to the following example. 此方法提供安全執行緒方式,只初始化單一已連接的 ConnectionMultiplexer 執行個體。This approach provides a thread-safe way to initialize only a single connected ConnectionMultiplexer instance. 在這些範例中, abortConnect 已設為 false,這表示即使無法建立與 Azure Redis 快取的連線,呼叫也會成功。In these examples 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.

private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
    return ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
});

public static ConnectionMultiplexer Connection
{
    get
    {
        return lazyConnection.Value;
    }
}

如需進階連線組態選項的詳細資訊,請參閱 StackExchange.Redis 組態模型For more information on advanced connection configuration options, see StackExchange.Redis configuration model.

若要連接到 Azure Redis 快取執行個體,快取用戶端需要主機名稱、連接埠和快取金鑰。To connect to an Azure Redis Cache instance, cache clients need the host name, ports, and keys of the cache. 某些用戶端可能會以稍有不同的名稱來參考這些項目。Some clients may refer to these items by slightly different names. 您可以在 Azure 入口網站中或使用 Azure CLI 等命令列工具來擷取此資訊。You can retrieve this information in the Azure portal or by using command-line tools such as Azure CLI.

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

若要使用 Azure 入口網站來擷取主機名稱、連接埠及存取金鑰,請在 Azure 入口網站瀏覽至您的快取,然後按一下 [資源] 功能表中的 [存取金鑰] 和 [屬性]。To retrieve host name, ports, and access keys using the Azure Portal, browse to your cache in the Azure portal and click Access keys and Properties in the Resource menu.

Redis 快取設定

使用 Azure CLI 來擷取主機名稱、連接埠及存取金鑰Retrieve host name, ports, and access keys using Azure CLI

若要使用 Azure CLI 2.0 來擷取主機名稱和連接埠,您可以呼叫 az redis show,而若要擷取金鑰,您可以呼叫 az redis list-keysTo retrieve the host name and ports using Azure CLI 2.0 you can call az redis show, and to retrieve the keys you can call az redis list-keys. 下列指令碼會呼叫下列兩個命令,並將主機名稱、連接埠和金鑰回應到主控台。The following script calls these two commands and echos the hostname, ports, and keys to the console.

#/bin/bash

# Retrieve the hostname, ports, and keys for contosoCache located in contosoGroup

# Retrieve the hostname and ports for an Azure Redis Cache instance
redis=($(az redis show --name contosoCache --resource-group contosoGroup --query [hostName,enableNonSslPort,port,sslPort] --output tsv))

# Retrieve the keys for an Azure Redis Cache instance
keys=($(az redis list-keys --name contosoCache --resource-group contosoGroup --query [primaryKey,secondaryKey] --output tsv))

# Display the retrieved hostname, keys, and ports
echo "Hostname:" ${redis[0]}
echo "Non SSL Port:" ${redis[2]}
echo "Non SSL Port Enabled:" ${redis[1]}
echo "SSL Port:" ${redis[3]}
echo "Primary Key:" ${keys[0]}
echo "Secondary Key:" ${keys[1]}

如需有關此指令碼的詳細資訊,請參閱取得 Azure Redis 快取的主機名稱、連接埠和金鑰For more information about this script, see Get the hostname, ports, and keys for Azure Redis Cache. 如需有關 Azure CLI 2.0 的詳細資訊,請參閱安裝 Azure CLI 2.0開始使用 Azure CLI 2.0For more information on Azure CLI 2.0, see Install Azure CLI 2.0 and Get started with Azure CLI 2.0.

一旦建立連線,即會透過呼叫 ConnectionMultiplexer.GetDatabase 方法傳回 Redis 快取資料庫的參考。Once the connection is established, return a reference to the redis cache database by calling the ConnectionMultiplexer.GetDatabase method. 透過 GetDatabase 方法傳回的物件是輕量型傳遞物件,而且不需要儲存。The object returned from the GetDatabase method is a lightweight pass-through object and does not need to be stored.

// Connection refers to a property that returns a ConnectionMultiplexer
// as shown in the previous example.
IDatabase cache = Connection.GetDatabase();

// Perform cache operations using the cache object...
// Simple put of integral data types into the cache
cache.StringSet("key1", "value");
cache.StringSet("key2", 25);

// Simple get of data types from the cache
string key1 = cache.StringGet("key1");
int key2 = (int)cache.StringGet("key2");

Azure Redis 快取具有可供用來以邏輯方式區隔 Redis 快取內資料的可設定數目資料庫 (預設值為 16 個)。Azure Redis caches have a configurable number of databases (default of 16) that can be used to logically separate the data within a Redis cache. 如需詳細資訊,請參閱 Redis 資料庫是什麼?預設 Redis 伺服器組態For more information, see What are Redis databases? and Default Redis server configuration.

現在您知道如何連線至 Azure Redis 快取執行個體,並傳回快取資料庫的參考,讓我們來看看如何使用快取。Now that you know how to connect to an Azure Redis Cache instance and return a reference to the cache database, let's look at working with the cache.

從快取新增和擷取物件Add and retrieve objects from the cache

您可以使用 StringSetStringGet 方法,在快取中儲存或擷取項目。Items can be stored in and retrieved from a cache by using the StringSet and StringGet methods.

// If key1 exists, it is overwritten.
cache.StringSet("key1", "value1");

string value = cache.StringGet("key1");

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.

呼叫 StringGet 時,如果物件已存在,即會傳回,如果物件不存在,則會傳回 nullWhen calling StringGet, if the object exists, it is returned, and if it does not, null is returned. 如果傳回 null,您可以從需要的資料來源中擷取值,並將它儲存在快取中供後續使用。If null is returned, you can retrieve the value from the desired data source and store it in the cache for subsequent use. 這種使用模式稱為另行快取模式。This usage pattern is known as the cache-aside pattern.

string value = cache.StringGet("key1");
if (value == null)
{
    // The item keyed by "key1" is not in the cache. Obtain
    // it from the desired data source and add it to the cache.
    value = GetValueFromDataSource();

    cache.StringSet("key1", value);
}

您也可以使用 RedisValue,如下列範例所示。You can also use RedisValue, as shown in the following example. RedisValue 有隱含的運算子適用於整數資料類型,而如果 null 是預期的快取項目值則很實用。RedisValue has implicit operators for working with integral data types, and can be useful if null is an expected value for a cached item.

RedisValue value = cache.StringGet("key1");
if (!value.HasValue)
{
    value = GetValueFromDataSource();
    cache.StringSet("key1", value);
}

若要指定快取中項目的到期時間,請使用 StringSetTimeSpan 參數。To specify the expiration of an item in the cache, use the TimeSpan parameter of StringSet.

cache.StringSet("key1", "value1", TimeSpan.FromMinutes(90));

使用快取中的 .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.NET 中的 JsonConvert 序列化方法並進行 JSON 的雙向序列化。One simple way to serialize objects is to use the JsonConvert serialization methods in Newtonsoft.Json.NET and serialize to and from JSON. 下列範例使用 Employee 物件執行個體顯示 get 和 set。The following example shows a get and set using an Employee object instance.

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

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

// Store to cache
cache.StringSet("e25", JsonConvert.SerializeObject(new Employee(25, "Clayton Gragg")));

// Retrieve from cache
Employee e25 = JsonConvert.DeserializeObject<Employee>(cache.StringGet("e25"));

後續步驟Next Steps

了解基礎概念之後,請依照下列連結深入了解 Azure Redis 快取。Now that you've learned the basics, follow these links to learn more about Azure Redis Cache.