从托管缓存服务迁移到 Azure Redis 缓存(已弃用)Migrate from Managed Cache Service to Azure Cache for Redis (deprecated)

在将使用 Azure 托管缓存服务的应用程序迁移到 Azure Redis 缓存时,只需对应用程序略做更改,具体情况取决于缓存应用程序所使用的托管缓存服务功能。Migrating your applications that use Azure Managed Cache Service to Azure Cache for Redis can be accomplished with minimal changes to your application, depending on the Managed Cache Service features used by your caching application. API 虽非完全相同,但却极为类似,而且使用托管缓存服务来访问缓存的多数现有代码,只需略做更改即可重复使用。While the APIs are not exactly the same they are similar, and much of your existing code that uses Managed Cache Service to access a cache can be reused with minimal changes. 本文介绍了为迁移托管缓存服务应用程序以使用 Azure Redis 缓存,如何进行必要的配置和应用程序更改;还介绍了如何使用 Azure Redis 缓存的某些功能实现托管缓存服务缓存功能。This article shows how to make the necessary configuration and application changes to migrate your Managed Cache Service applications to use Azure Cache for Redis, and shows how some of the features of Azure Cache for Redis can be used to implement the functionality of a Managed Cache Service cache.

备注

托管缓存服务和角色中缓存在 2016 年 11 月 30 日停用Managed Cache Service and In-Role Cache were retired November 30, 2016. 如果要将角色中缓存部署迁移到 Azure Redis 缓存,可按照本文中的步骤执行。If you have any In-Role Cache deployments that you want to migrate to Azure Cache for Redis, you can follow the steps in this article.

迁移步骤Migration Steps

要将托管缓存服务应用程序迁移为使用 Azure Redis 缓存,需执行以下步骤。The following steps are required to migrate a Managed Cache Service application to use Azure Cache for Redis.

  • 将托管缓存服务功能映射到 Azure Redis 缓存Map Managed Cache Service features to Azure Cache for Redis
  • 选择缓存产品/服务Choose a Cache Offering
  • 创建缓存Create a Cache
  • 配置缓存客户端Configure the Cache Clients
    • 删除托管缓存服务配置Remove the Managed Cache Service Configuration
    • 使用 StackExchange.Redis NuGet 包配置缓存客户端Configure a cache client using the StackExchange.Redis NuGet Package
  • 迁移托管缓存服务代码Migrate Managed Cache Service code
    • 使用 ConnectionMultiplexer 类连接到缓存Connect to the cache using the ConnectionMultiplexer class
    • 访问缓存中的基元数据类型Access primitive data types in the cache
    • 处理缓存中的 .NET 对象Work with .NET objects in the cache
  • 将 ASP.NET 会话状态和输出缓存迁移到 Azure Redis 缓存Migrate ASP.NET Session State and Output caching to Azure Cache for Redis

将托管缓存服务功能映射到 Azure Redis 缓存Map Managed Cache Service features to Azure Cache for Redis

Azure 托管缓存服务与 Azure Redis 缓存类似,但两者在实现某些功能时会使用不同的方式。Azure Managed Cache Service and Azure Cache for Redis are similar but implement some of their features in different ways. 本节描述其中的一些差异,并针对如何在 Azure Redis 缓存中实现托管缓存服务功能提供指导。This section describes some of the differences and provides guidance on implementing the features of Managed Cache Service in Azure Cache for Redis.

托管缓存服务功能Managed Cache Service feature 托管缓存服务支持Managed Cache Service support Azure Redis 缓存支持Azure Cache for Redis support
命名缓存Named caches 系统会配置默认缓存,而在标准和高级缓存产品/服务中,还可以根据需要额外配置多达 9 个命名缓存。A default cache is configured, and in the Standard and Premium cache offerings, up to nine additional named caches can be configured if desired. Azure Redis 缓存具有可配置数量的数据库(默认值为 16 个),可用于实现与命名缓存类似的功能。Azure Cache for Redis has a configurable number of databases (default of 16) that can be used to implement a similar functionality to named caches. 有关详细信息,请参阅什么是 Redis 数据库?默认 Redis 服务器配置For more information, see What are Redis databases? and Default Redis server configuration.
高可用性High Availability 在标准和高级缓存产品/服务中,为缓存中的项提供高可用性。Provides high availability for items in the cache in the Standard and Premium cache offerings. 如果因为故障而导致项丢失,缓存中的项仍有备份副本可供使用。If items are lost due to a failure, backup copies of the items in the cache are still available. 副本缓存的写入操作以同步方式进行。Writes to the replica cache are made synchronously. 标准和高级缓存产品/服务提供高可用性,它们具有双节点的主要/副本配置(高级缓存的每个分片都有主要/副本对)。High availability is available in the Standard and Premium cache offerings, which have a two node Primary/Replica configuration (each shard in a Premium cache has a primary/replica pair). 副本的写入操作以异步方式进行。Writes to the replica are made asynchronously. 有关详细信息,请参阅 Azure Redis 缓存定价For more information, see Azure Cache for Redis pricing.
通知Notifications 当命名缓存上发生各种缓存操作时,允许客户端接收异步通知。Allows clients to receive asynchronous notifications when a variety of cache operations occur on a named cache. 客户端应用程序可以使用 Redis pub/sub 或密钥空间通知来实现与通知类似的功能。Client applications can use Redis pub/sub or Keyspace notifications to achieve a similar functionality to notifications.
本地缓存Local cache 在客户端本地存储缓存对象的副本,以实现超快访问。Stores a copy of cached objects locally on the client for extra-fast access. 客户端应用程序需使用字典或类似的数据结构来实现此功能。Client applications would need to implement this functionality using a dictionary or similar data structure.
逐出策略Eviction Policy 无或 LRU。None or LRU. 默认策略是 LRU。The default policy is LRU. Azure Redis 缓存支持以下逐出策略:volatile-lru、allkeys-lru、volatile-random、allkeys-random、volatile-ttl、noeviction。Azure Cache for Redis supports the following eviction policies: volatile-lru, allkeys-lru, volatile-random, allkeys-random, volatile-ttl, noeviction. 默认策略是 volatile-lru。The default policy is volatile-lru. 有关详细信息,请参阅默认 Redis 服务器配置For more information, see Default Redis server configuration.
过期策略Expiration Policy 默认过期策略为“绝对”,默认过期间隔为 10 分钟。The default expiration policy is Absolute and the default expiration interval is 10 minutes. 另外也提供“滑动”和“永不”策略。Sliding and Never policies are also available. 默认情况下,缓存中的项不会过期,但可以使用缓存集重载,对每次写入配置过期时间。By default items in the cache do not expire, but an expiration can be configured on a per write basis using cache set overloads.
区域和标记Regions and Tagging 区域是缓存项的子组。Regions are subgroups for cached items. 区域也支持使用称为标记的额外描述性字符串为缓存项添加批注。Regions also support the annotation of cached items with additional descriptive strings called tags. 区域支持对该区域内的任何标记项执行搜索操作的能力。Regions support the ability to perform search operations on any tagged items in that region. 区域内的所有项全部位于缓存群集的单个节点内。All items within a region are located within a single node of the cache cluster. Azure Redis 缓存由单个节点组成(除非已启用 Redis 群集),因此托管缓存服务区域的概念不适用。an Azure Cache for Redis consists of a single node (unless Redis cluster is enabled) so the concept of Managed Cache Service regions does not apply. Redis 支持在检索键时执行搜索和通配符操作,让描述性标记可以嵌入键名称内并在后面用于检索项。Redis supports searching and wildcard operations when retrieving keys so descriptive tags can be embedded within the key names and used to retrieve the items later. 有关使用 Redis 实现标记解决方案的示例,请参阅使用 Redis 实现缓存标记For an example of implementing a tagging solution using Redis, see Implementing cache tagging with Redis.
序列化Serialization 托管缓存支持 NetDataContractSerializer 和 BinaryFormatter,也支持使用自定义序列化程序。Managed Cache supports NetDataContractSerializer, BinaryFormatter, and the use of custom serializers. 默认值为 NetDataContractSerializer。The default is NetDataContractSerializer. 由客户端应用程序负责先将 .NET 对象序列化,再将它们放入缓存中,至于要选择使用哪个序列化程序则由客户端应用程序开发人员决定。It is the responsibility of the client application to serialize .NET objects before placing them into the cache, with the choice of the serializer up to the client application developer. 有关详细信息和示例代码,请参阅处理缓存中的 .NET 对象For more information and sample code, see Work with .NET objects in the cache.
缓存模拟器Cache emulator 托管缓存提供本地缓存模拟器。Managed Cache provides a local cache emulator. 用于 Redis 的 Azure 缓存没有模拟器,但可以通过在本地运行 Redis 来提供模拟器体验。Azure Cache for Redis does not have an emulator, but you can run Redis locally to provide an emulator experience.

选择缓存产品/服务Choose a Cache Offering

Azure Redis 缓存在下述层中提供:Azure Cache for Redis 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 到 1.2 TB)。Multiple sizes from 6 GB to 1.2 TB. 标准层的所有功能加上其他功能,包括支持 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. 在本指南的后面将介绍这些功能,而有关定价的详细信息,则请参阅缓存定价详细信息The features are covered later in this guide, and for more information on pricing, see Cache Pricing Details.

迁移操作的第一步是选择与以前的托管缓存服务缓存大小匹配的大小,并根据应用程序的需求进行增减。A starting point for migration is to pick the size that matches the size of your previous Managed Cache Service cache, and then scale up or down depending on the requirements of your application. 有关如何选择合适的 Azure Cache for Redis 产品/服务的详细信息,请参阅选择合适的层For more information on choosing the right Azure Cache for Redis offering, see Choosing the right tier.

创建缓存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.chinacloudapi.cnYour 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.
    位置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. 有关详细信息,请参阅用于 Redis 的 Azure 缓存概述For more information, see Azure Cache for Redis Overview.
  4. 选择“创建” 。Select Create.

    创建 Azure Redis 缓存

    备注

    缓存预配大约需要 15 到 20 分钟。You can expect the provisioning of the Cache to take around 15 to 20 minutes.

    可以在 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 缓存

配置缓存客户端Configure the Cache Clients

创建并配置缓存后,接下来就是删除托管缓存服务配置,并添加 Azure Redis 缓存配置和引用,让缓存客户端可以访问缓存。Once the cache is created and configured, the next step is to remove the Managed Cache Service configuration, and add the Azure Cache for Redis configuration and references so that cache clients can access the cache.

  • 删除托管缓存服务配置Remove the Managed Cache Service Configuration
  • 使用 StackExchange.Redis NuGet 包配置缓存客户端Configure a cache client using the StackExchange.Redis NuGet Package

删除托管缓存服务配置Remove the Managed Cache Service Configuration

要将客户端应用程序配置为使用 Azure Redis 缓存,必须先卸载托管缓存服务 NuGet 包,以便删除现有托管缓存服务的配置和组件引用。Before the client applications can be configured for Azure Cache for Redis, the existing Managed Cache Service configuration and assembly references must be removed by uninstalling the Managed Cache Service NuGet package.

要卸载托管缓存服务 NuGet 包,请在“解决方案资源管理器” 中右键单击客户端项目,并选择“管理 NuGet 程序包” 。To uninstall the Managed Cache Service NuGet package, right-click the client project in Solution Explorer and choose Manage NuGet Packages. 选择“已安装的包” 节点,并在“搜索已安装的包”框中键入 WindowsAzure.CachingSelect the Installed packages node, and type WindowsAzure.Caching into the Search installed packages box. 选择“Windows Azure Cache” (或“Windows Azure Caching” ,视 NuGet 包的版本而定),单击“卸载” ,并单击“关闭” 。Select Windows Azure Cache (or Windows Azure Caching depending on the version of the NuGet package), click Uninstall, and then click Close.

卸载 Azure 托管缓存服务 NuGet 包

卸载托管缓存服务 NuGet 包时,会删除客户端应用程序的 app.config 或 web.config 中的托管缓存服务组件和托管缓存服务条目。Uninstalling the Managed Cache Service NuGet package removes the Managed Cache Service assemblies and the Managed Cache Service entries in the app.config or web.config of the client application. 由于卸载 NuGet 包时可能不会删除有些自定义设置,因此请打开 web.config 或 app.config,确保已删除以下元素。Because some customized settings may not be removed when uninstalling the NuGet package, open web.config or app.config and ensure that the following elements are removed.

确保已从 configSections 元素中删除 dataCacheClients 条目。Ensure that the dataCacheClients entry is removed from the configSections element. 请勿删除整个 configSections 元素,只需删除 dataCacheClients 条目(如果存在)。Do not remove the entire configSections element; just remove the dataCacheClients entry, if it is present.

<configSections>
  <!-- Existing sections omitted for clarity. -->
  <section name="dataCacheClients"type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere"/>
</configSections>

确保已删除 dataCacheClients 节。Ensure that the dataCacheClients section is removed. dataCacheClients 节将类似于以下示例。The dataCacheClients section will be similar to the following example.

<dataCacheClients>
  <dataCacheClientname="default">
    <!--To use the in-role flavor of Azure Cache, set identifier to be the cache cluster role name -->
    <!--To use the Azure Managed Cache Service, set identifier to be the endpoint of the cache cluster -->
    <autoDiscoverisEnabled="true"identifier="[Cache role name or Service Endpoint]"/>

    <!--<localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />-->
    <!--Use this section to specify security settings for connecting to your cache. This section is not required if your cache is hosted on a role that is a part of your cloud service. -->
    <!--<securityProperties mode="Message" sslEnabled="true">
      <messageSecurity authorizationInfo="[Authentication Key]" />
    </securityProperties>-->
  </dataCacheClient>
</dataCacheClients>

一旦删除托管缓存服务配置,就可以如下一节所述配置缓存客户端。Once the Managed Cache Service configuration is removed, you can configure the cache client as described in the following section.

使用 StackExchange.Redis NuGet 包配置缓存客户端Configure a cache client using the StackExchange.Redis NuGet Package

.NET 应用程序可以使用 StackExchange.Redis 缓存客户端,可使用 NuGet 包在 Visual Studio 中进行配置,以简化缓存客户端应用程序的配置。.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.Azure Redis 缓存客户端文档For more information, see the StackExchange.Redis GitHub page and the StackExchange.Azure Cache for Redis client documentation.

如果要使用 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.

管理 NuGet 包

在“搜索”文本框中键入 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 程序包

NuGet 程序包会为客户端应用程序下载并添加所需的程序集引用,以通过 StackExchange.Azure Redis 缓存客户端访问 Azure Redis 缓存。The NuGet package downloads and adds the required assembly references for your client application to access Azure Cache for Redis with the StackExchange.Azure Cache for Redis 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 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.

也可安装 StackExchange.Redis NuGet 包,方法是:依次单击“工具”菜单中的“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

迁移托管缓存服务代码Migrate Managed Cache Service code

StackExchange.Azure Redis 缓存客户端的 API 与托管缓存服务类似。The API for the StackExchange.Azure Cache for Redis client is similar to the Managed Cache Service. 本节将概述两者的差异。This section provides an overview of the differences.

使用 ConnectionMultiplexer 类连接到缓存Connect to the cache using the ConnectionMultiplexer class

在托管缓存服务中,缓存连接由 DataCacheFactoryDataCache 类负责处理。In Managed Cache Service, connections to the cache were handled by the DataCacheFactory and DataCache classes. 在 Azure Redis 缓存中,这些连接则由 ConnectionMultiplexer 类进行管理。In Azure Cache for Redis, these connections are managed by the ConnectionMultiplexer class.

将以下 using 语句添加到要从中访问缓存的任何文件的顶部。Add the following using statement to the top of any file from which you want to access the cache.

using StackExchange.Redis

如果此命名空间并未解析,请确保已如快速入门:将 Azure Redis 缓存用于 .NET 应用程序中所述添加了 StackExchange.Redis NuGet 包。If this namespace doesn’t resolve, be sure that you have added the StackExchange.Redis NuGet package as described in Quickstart: Use Azure Cache for Redis with a .NET application.

备注

请注意,StackExchange.Redis 客户端需要 .NET Framework 4 或更高版本。Note that the StackExchange.Redis client requires .NET Framework 4 or higher.

若要连接到 Azure Redis 缓存实例,请调用静态 ConnectionMultiplexer.Connect 方法并传入终结点和密钥。To connect to an Azure Cache for Redis instance, call the static ConnectionMultiplexer.Connect method and pass in the endpoint and key. 共享应用程序中的 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 a single connected ConnectionMultiplexer instance. 在此示例中,abortConnect 设置为 false,这表示即使未建立缓存连接,也可成功调用。In this example abortConnect is set to false, which means that the call will succeed even if a connection to the cache is not established. ConnectionMultiplexer 的一个关键功能是,一旦还原网络问题和其他原因,它会自动还原缓存连接。One key feature of ConnectionMultiplexer is that it will automatically restore 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.chinacloudapi.cn,abortConnect=false,ssl=true,password=...");
});

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

可以从缓存实例的“Azure Redis 缓存” 边栏选项卡中获取缓存终结点、密钥和端口。The cache endpoint, keys, and ports can be obtained from the Azure Cache for Redis blade for your cache instance. 有关详细信息,请参阅 Azure Redis 缓存属性For more information, see Azure Cache for Redis properties.

建立连接后,通过调用 ConnectionMultiplexer.GetDatabase 方法返回对 Azure Redis 缓存数据库的引用。Once the connection is established, return a reference to the Azure Cache for Redis 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.

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

StackExchange.Redis 客户端使用 RedisKeyRedisValue 类型在缓存中访问和存储项。The StackExchange.Redis client uses the RedisKey and RedisValue types for accessing and storing items in the cache. 这些类型可映射到最基本的语言类型(包括字符串),但通常不直接使用。These types map onto most primitive language types, including string, and often are not used directly. Redis 字符串是最基本的一种 Redis 值,可包含许多类型的数据(包括序列化的二进制数据流),可能不会直接使用此类型,但你会使用在名称中包含 String 的方法。Redis Strings are the most basic kind of Redis value, and can contain many types of data, including serialized binary streams, and while you may not use the type directly, you will use methods that contain String in the name. 对于最基本的数据类型,会使用 StringSetStringGet 方法在缓存中存储和检索项,除非要在缓存中存储集合或其他 Redis 数据类型。For most primitive data types, you store and retrieve items from the cache using the StringSet and StringGet methods, unless you are storing collections or other Redis data types in the cache.

StringSetStringGet 类似于托管缓存服务的 PutGet 方法,其中最主要的差异在于,要设置 .NET 对象并将其放到缓存中,必须先将其序列化。StringSet and StringGet are similar to the Managed Cache Service Put and Get methods, with one major difference being that before you set and get a .NET object into the cache you must serialize it first.

调用 StringGet 时,如果该对象存在,则返回它,如果该对象不存在,则返回 null。When calling StringGet, if the object exists, it is returned, and if it does not, null is returned. 在这种情况下,可以从所需的数据源检索值,并将其存储在缓存中供后续使用。In this case, you can retrieve the value from the desired data source and store it in the cache for subsequent use. 此模式称为缓存端模式。This pattern is known as the cache-aside pattern.

要在缓存中指定项的过期时间,请使用 StringSetTimeSpan 参数。To specify the expiration of an item in the cache, use the TimeSpan parameter of StringSet.

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

Azure Redis 缓存可以处理 .NET 对象以及基元数据类型,但在缓存 .NET 对象之前,必须先将其序列化。Azure Cache for Redis can work with .NET objects as well as primitive data types, but before a .NET object can be cached it must be serialized. 此序列化是应用程序开发人员的责任,同时赋与开发人员选择序列化程序的灵活性。This serialization is the responsibility of the application developer, and gives the developer flexibility in the choice of the serializer. 有关详细信息和示例代码,请参阅处理缓存中的 .NET 对象For more information and sample code, see Work with .NET objects in the cache.

将 ASP.NET 会话状态和输出缓存迁移到 Azure Redis 缓存Migrate ASP.NET Session State and Output caching to Azure Cache for Redis

Azure Redis 缓存有适用于 ASP.NET 会话状态和页面输出缓存的提供程序。Azure Cache for Redis has providers for both ASP.NET Session State and Page Output caching. 要迁移使用这些提供程序的托管缓存服务版本的应用程序,请先从 web.config 中删除现有节,然后配置这些提供程序的 Azure Redis 缓存版本。To migrate your application that uses the Managed Cache Service versions of these providers, first remove the existing sections from your web.config, and then configure the Azure Cache for Redis versions of the providers. 有关使用 Azure Redis 缓存 ASP.NET 提供程序的说明,请参阅 Azure Redis 缓存的 ASP.NET 会话状态提供程序Azure Redis 缓存的 ASP.NET 输出缓存提供程序For instructions on using the Azure Cache for Redis ASP.NET providers, see ASP.NET Session State Provider for Azure Cache for Redis and ASP.NET Output Cache Provider for Azure Cache for Redis.

后续步骤Next steps

浏览 Azure Redis 缓存文档中的教程、示例、视频及其他信息。Explore the Azure Cache for Redis documentation for tutorials, samples, videos, and more.