Azure Redis 缓存的 ASP.NET 输出缓存提供程序ASP.NET Output Cache Provider for Azure Cache for Redis

Redis 输出缓存提供程序是用于输出缓存数据的进程外存储机制。The Redis Output Cache Provider is an out-of-process storage mechanism for output cache data. 此数据专门用于完整 HTTP 响应(页面输出缓存)。This data is specifically for full HTTP responses (page output caching). 此提供程序会插入 ASP.NET 4 中引入的新输出缓存提供程序扩展点。The provider plugs into the new output cache provider extensibility point that was introduced in ASP.NET 4.

要使用 Redis 输出缓存提供程序,首先配置用户的缓存,然后使用 Redis 输出缓存提供程序 NuGet 包配置 ASP.NET 应用程序。To use the Redis Output Cache Provider, first configure your cache, and then configure your ASP.NET application using the Redis Output Cache Provider NuGet package. 本主题提供有关配置应用程序以使用 Redis 输出缓存提供程序的指南。This topic provides guidance on configuring your application to use the Redis Output Cache Provider. 有关创建和配置 Azure Redis 缓存实例的详细信息,请参阅创建缓存For more information about creating and configuring an Azure Cache for Redis instance, see Create a cache.

在缓存中存储 ASP.NET 页面输出Store ASP.NET page output in the cache

要使用 Azure Redis 缓存会话状态 NuGet 包在 Visual Studio 中配置客户端应用程序,请在“工具”菜单中依次单击“NuGet 包管理器”和“包管理器控制台” 。To configure a client application in Visual Studio using the Azure Cache for Redis Session State NuGet package, click NuGet Package Manager, Package Manager Console from the Tools menu.

Package Manager Console 窗口运行以下命令。Run the following command from the Package Manager Console window.

Install-Package Microsoft.Web.RedisOutputCacheProvider

Redis 输出缓存提供程序 NuGet 包依赖于 StackExchange.Redis.StrongName 包。The Redis Output Cache Provider NuGet package has a dependency on the StackExchange.Redis.StrongName package. 如果项目中没有 StackExchange.Redis.StrongName 包,则会安装它。If the StackExchange.Redis.StrongName package is not present in your project, it is installed. 有关 Redis 输出缓存提供程序 NuGet 包的详细信息,请参阅 RedisOutputCacheProvider NuGet 页。For more information about the Redis Output Cache Provider NuGet package, see the RedisOutputCacheProvider NuGet page.

备注

除了强命名的 StackExchange.Redis.StrongName 包外,还有 StackExchange.Redis 非强命名版本。In addition to the strong-named StackExchange.Redis.StrongName package, there is also the StackExchange.Redis non-strong-named version. 如果项目使用非强命名的 StackExchange.Redis 版本,则必须将其卸载,否则会在项目中遇到命名冲突。If your project is using the non-strong-named StackExchange.Redis version you must uninstall it; otherwise, you will experience naming conflicts in your project. 有关这些包的详细信息,请参阅配置 .NET 缓存客户端For more information about these packages, see Configure .NET cache clients.

NuGet 包会下载并添加所需的程序集引用,并将以下节添加到 web.config 文件中。The NuGet package downloads and adds the required assembly references and adds the following section into your web.config file. 此节包含的配置是 ASP.NET 应用程序使用 Redis 输出缓存提供程序所必需的。This section contains the required configuration for your ASP.NET application to use the Redis Output Cache Provider.

<caching>
  <outputCache defaultProvider="MyRedisOutputCache">
    <providers>
      <add name="MyRedisOutputCache" type="Microsoft.Web.Redis.RedisOutputCacheProvider"
           host=""
           accessKey=""
           ssl="true" />
    </providers>
  </outputCache>
</caching>

使用来自 Azure 门户中的缓存边栏选项卡的值配置属性,并根据需要配置其他值。Configure the attributes with the values from your cache blade in the Azure portal, and configure the other values as desired. 有关访问缓存属性的说明,请参阅配置 Azure Redis 缓存设置For instructions on accessing your cache properties, see Configure Azure Cache for Redis settings.

属性Attribute 类型Type 默认Default 说明Description
hosthost stringstring "localhost""localhost" Redis 服务器 IP 地址或主机名The Redis server IP address or host name
portport 正整数positive integer 6379(非 SSL)6379 (non-SSL)
6380 (SSL)6380 (SSL)
Redis 服务器端口Redis server port
accessKeyaccessKey stringstring """" 启用 Redis 授权时的 Redis 服务器密码。Redis server password when Redis authorization is enabled. 该值默认为空字符串,即,会话状态提供程序在连接到 Redis 服务器时不使用任何密码。The value is empty string by default, which means the session state provider won’t use any password when connecting to Redis server. 如果 Redis 服务器位于 Azure Redis 缓存等可公开访问的网络中,请务必启用 Redis 授权以提高安全性,并提供安全密码。If your Redis server is in a publicly accessible network like Azure Redis Cache, be sure to enable Redis authorization to improve security, and provide a secure password.
sslssl 布尔值boolean falsefalse 是否通过 SSL 连接到 Redis 服务器。Whether to connect to Redis server via SSL. 此值默认为 false,因为 Redis 不能现成地支持 SSL。This value is false by default because Redis doesn’t support SSL out of the box. 如果使用现成支持 SSL 的 Azure Redis 缓存,请务必将此属性设置为 true,以提高安全性。If you are using Azure Redis Cache which supports SSL out of the box, be sure to set this to true to improve security.

默认情况下,为新缓存禁用非 SSL 端口。The non-SSL port is disabled by default for new caches. 为此设置指定 true 可使用 SSL 端口。Specify true for this setting to use the SSL port. 有关启用非 SSL 端口的详细信息,请参阅配置缓存主题中的访问端口部分。For more information about enabling the non-SSL port, see the Access Ports section in the Configure a cache topic.
databaseIdNumberdatabaseIdNumber 正整数positive integer 00 只能通过 web.config 或 AppSettings 指定此属性。 This attribute can be specified only through either web.config or AppSettings.

指定要使用的 Redis 数据库。Specify which Redis database to use.
connectionTimeoutInMillisecondsconnectionTimeoutInMilliseconds 正整数positive integer 由 StackExchange.Redis 提供Provided by StackExchange.Redis 用于在创建 StackExchange.Redis.ConnectionMultiplexer 时设置 ConnectTimeoutUsed to set ConnectTimeout when creating StackExchange.Redis.ConnectionMultiplexer.
operationTimeoutInMillisecondsoperationTimeoutInMilliseconds 正整数positive integer 由 StackExchange.Redis 提供Provided by StackExchange.Redis 用于在创建 StackExchange.Redis.ConnectionMultiplexer 时设置 SyncTimeoutUsed to set SyncTimeout when creating StackExchange.Redis.ConnectionMultiplexer.
connectionString(有效的 StackExchange.Redis 连接字符串)connectionString (Valid StackExchange.Redis connection string) stringstring n/an/a 对 AppSettings 或 web.config 的参数引用,或有效的 StackExchange.Redis 连接字符串。Either a parameter reference to AppSettings or web.config, or else a valid StackExchange.Redis connection string. 此属性可提供 hostportaccessKeyssl 和其他 StackExchange.Redis 属性的值。This attribute can provide values for host, port, accessKey, ssl, and other StackExchange.Redis attributes. 若要更详细地了解 connectionString,请参阅属性说明部分中的设置 connectionStringFor a closer look at connectionString, see Setting connectionString in the Attribute notes section.
settingsClassNamesettingsClassName
settingsMethodNamesettingsMethodName
stringstring
stringstring
n/an/a 只能通过 web.config 或 AppSettings 指定这些属性。 These attributes can be specified only through either web.config or AppSettings.

使用这些属性提供连接字符串。Use these attributes to provide a connection string. settingsClassName 应是程序集限定的类名,其中包含 settingsMethodName 指定的方法。settingsClassName should be an assembly qualified class name that contains the method specified by settingsMethodName.

settingsMethodName 指定的方法应是 public、static 和 void(不采用任何参数),其返回类型为 stringThe method specified by settingsMethodName should be public, static, and void (not take any parameters), with a return type of string. 此方法返回实际的连接字符串。This method returns the actual connection string.
loggingClassNameloggingClassName
loggingMethodNameloggingMethodName
stringstring
stringstring
n/an/a 只能通过 web.config 或 AppSettings 指定这些属性。 These attributes can be specified only through either web.config or AppSettings.

使用这些属性可以通过提供会话状态/输出缓存的日志以及 StackExchange.Redis 的日志,来调试应用程序。Use these attributes to debug your application by providing logs from Session State/Output Cache along with logs from StackExchange.Redis. loggingClassName 应是程序集限定的类名,其中包含 loggingMethodName 指定的方法。loggingClassName should be an assembly qualified class name that contains the method specified by loggingMethodName.

loggingMethodName 指定的方法应是 public、static 和 void(不采用任何参数),其返回类型为 System.IO.TextWriterThe method specified by loggingMethodName should be public, static, and void (not take any parameters), with a return type of System.IO.TextWriter.
applicationNameapplicationName stringstring 当前进程的模块名称,或“/”The module name of the current process or "/" 仅限 SessionStateProvider SessionStateProvider only
只能通过 web.config 或 AppSettings 指定此属性。 This attribute can be specified only through either web.config or AppSettings.

要在 Redis 缓存中使用的应用名称前缀。The app name prefix to use in Redis cache. 客户可以使用相同的 Redis 缓存来实现不同的目的。The customer may use the same Redis cache for different purposes. 为了确保会话密钥不冲突,可以使用应用程序名称作为 Redis 缓存的前缀。To insure that the session keys do not collide, it can be prefixed with the application name.
throwOnErrorthrowOnError 布尔值boolean true 仅限 SessionStateProvider SessionStateProvider only
只能通过 web.config 或 AppSettings 指定此属性。 This attribute can be specified only through either web.config or AppSettings.

出错时是否引发异常。Whether to throw an exception when an error occurs.

有关 throwOnError 的详细信息,请参阅属性说明部分中的有关 throwOnError 的说明For more about throwOnError, see Notes on throwOnError in the Attribute notes section.
>Microsoft.Web.Redis.RedisSessionStateProvider.LastException>Microsoft.Web.Redis.RedisSessionStateProvider.LastException.
retryTimeoutInMillisecondsretryTimeoutInMilliseconds 正整数positive integer 50005000 仅限 SessionStateProvider SessionStateProvider only
只能通过 web.config 或 AppSettings 指定此属性。 This attribute can be specified only through either web.config or AppSettings.

操作失败时要重试多长时间。How long to retry when an operation fails. 如果此值小于 operationTimeoutInMilliseconds,则提供程序不会重试。If this value is less than operationTimeoutInMilliseconds, the provider will not retry.

有关 retryTimeoutInMilliseconds 的详细信息,请参阅属性说明部分中的有关 retryTimeoutInMilliseconds 的说明For more about retryTimeoutInMilliseconds, see Notes on retryTimeoutInMilliseconds in the Attribute notes section.
redisSerializerTyperedisSerializerType stringstring n/an/a 指定某个类的程序集限定类型名称,该类实现 Microsoft.Web.Redis.Specifies the assembly qualified type name of a class that implements Microsoft.Web.Redis. ISerializer,且包含用于序列化和反序列化值的自定义逻辑。ISerializer and that contains the custom logic to serialize and deserialize the values. 有关详细信息,请参阅属性说明部分中的关于 redisSerializerTypeFor more information, see About redisSerializerType in the Attribute notes section.

属性说明Attribute notes

设置 connectionStringSetting connectionString

connectionString 的值用作密钥,从 AppSettings 中提取实际的连接字符串(如果 AppSettings 中存在此类字符串)。The value of connectionString is used as key to fetch the actual connection string from AppSettings, if such a string exists in AppSettings. 如果在 AppSettings 中未找到此字符串,connectionString 的值将用作密钥,从 web.config 的 ConnectionString 节(如果存在该节)中提取实际的连接字符串。If not found inside AppSettings, the value of connectionString will be used as key to fetch actual connection string from the web.config ConnectionString section, if that section exists. 如果 AppSettings 或 web.config 的 ConnectionString 节中不存在该连接字符串,则创建 StackExchange.Redis.ConnectionMultiplexer 时,会将 connectionString 的文本值用作连接字符串。If the connection string does not exists in AppSettings or the web.config ConnectionString section, the literal value of connectionString will be used as the connection string when creating StackExchange.Redis.ConnectionMultiplexer.

以下示例演示如何使用 connectionStringThe following examples illustrate how connectionString is used.

示例 1Example 1

<connectionStrings>
    <add name="MyRedisConnectionString" connectionString="mycache.redis.cache.chinacloudapi.cn:6380,password=actual access key,ssl=True,abortConnect=False" />
</connectionStrings>

web.config 中,使用上述密钥作为参数值而不是实际值。In web.config, use above key as parameter value instead of actual value.

<sessionState mode="Custom" customProvider="MySessionStateStore">
    <providers>
        <add type = "Microsoft.Web.Redis.RedisSessionStateProvide"
             name = "MySessionStateStore"
             connectionString = "MyRedisConnectionString"/>
    </providers>
</sessionState>

示例 2Example 2

<appSettings>
    <add key="MyRedisConnectionString" value="mycache.redis.cache.chinacloudapi.cn:6380,password=actual access key,ssl=True,abortConnect=False" />
</appSettings>

web.config 中,使用上述密钥作为参数值而不是实际值。In web.config, use above key as parameter value instead of actual value.

<sessionState mode="Custom" customProvider="MySessionStateStore">
    <providers>
        <add type = "Microsoft.Web.Redis.RedisSessionStateProvide"
             name = "MySessionStateStore"
             connectionString = "MyRedisConnectionString"/>
    </providers>
</sessionState>

示例 3Example 3

<sessionState mode="Custom" customProvider="MySessionStateStore">
    <providers>
        <add type = "Microsoft.Web.Redis.RedisSessionStateProvide"
             name = "MySessionStateStore"
             connectionString = "mycache.redis.cache.chinacloudapi.cn:6380,password=actual access key,ssl=True,abortConnect=False"/>
    </providers>
</sessionState>

有关 throwOnError 的说明Notes on throwOnError

目前,如果在会话操作期间出错,则会话状态提供程序将引发异常。Currently, if an error occurs during a session operation, the session state provider will throw an exception. 这会关闭应用程序。This shuts down the application.

此行为现已经过修改,符合现有 ASP.NET 会话状态提供程序用户的预期,同时还提供按需处理异常的功能。This behavior has been modified in a way that supports the expectations of existing ASP.NET session state provider users while also providing the ability to act on exceptions, if desired. 默认行为仍会在出错时引发异常,这与其他 ASP.NET 会话状态提供程序相一致;现有代码应可如过去一样正常运行。The default behavior still throws an exception when an error occurs, consistent with other ASP.NET session state providers; existing code should work the same as before.

如果将 throwOnError 设置为 false,则出错时不会引发异常,而是以无提示方式失败。If you set throwOnError to false, then instead of throwing an exception when an error occurs, it will fail silently. 若要查看是否已出错,从而发现具体的异常是什么,请检查静态属性 Microsoft.Web.Redis.RedisSessionStateProvider.LastExceptionTo see if there was an error and, if so, discover what the exception was, check the static property Microsoft.Web.Redis.RedisSessionStateProvider.LastException.

有关 retryTimeoutInMilliseconds 的说明Notes on retryTimeoutInMilliseconds

此属性提供某种重试逻辑来简化以下方案:某项会话操作因网络小故障等问题失败时应该重试,同时允许控制重试超时,或完全禁用重试。This provides some retry logic to simplify the case where some session operation should retry on failure because of things like network glitch, while also allowing you to control the retry timeout or opt out of retry entirely.

如果将 retryTimeoutInMilliseconds 设置为某个数字(例如 2000),则当会话操作失败时,它会重试 2000 毫秒,如果仍然失败,系统将认为出错。If you set retryTimeoutInMilliseconds to a number, for example 2000, then when a session operation fails, it will retry for 2000 milliseconds before treating it as an error. 因此,若要让会话状态提供程序应用此重试逻辑,只需配置超时即可。So to have the session state provider to apply this retry logic, just configure the timeout. 首次重试发生在 20 毫秒之后,在大多数情况下,发生网络小故障时,此时间已足够。The first retry will happen after 20 milliseconds, which is sufficient in most cases when a network glitch happens. 此后,操作会每隔一秒重试一次,直到超时。超时过后,操作会紧接着再试一次,以确保不会将超时终止(最多)一秒。After that, it will retry every second until it times out. Right after the time out, it will retry one more time to make sure that it won’t cut off the timeout by (at most) one second.

如果你认为不需要重试(例如,在应用程序所在的同一台计算机上运行 Redis 服务器时),或者要自行处理重试逻辑,请将 retryTimeoutInMilliseconds 设置为 0。If you don’t think you need retry (for example, when you are running the Redis server on the same machine as your application) or if you want to handle the retry logic yourself, set retryTimeoutInMilliseconds to 0.

关于 redisSerializerTypeAbout redisSerializerType

默认情况下,用于在 Redis 上存储值的序列化是以 BinaryFormatter 类提供的二进制格式完成的。By default, the serialization to store the values on Redis is done in a binary format provided by the BinaryFormatter class. 使用 redisSerializerType 可以指定某个类的程序集限定类型名称,该类实现 Microsoft.Web.Redis.ISerializer,且包含用于序列化和反序列化值的自定义逻辑。Use redisSerializerType to specify the assembly qualified type name of a class that implements Microsoft.Web.Redis.ISerializer and has the custom logic to serialize and deserialize the values. 例如,下面是一个使用 JSON.NET 的 JSON 序列化程序类:For example, here is a Json serializer class using JSON.NET:

namespace MyCompany.Redis
{
    public class JsonSerializer : ISerializer
    {
        private static JsonSerializerSettings _settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };

        public byte[] Serialize(object data)
        {
            return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data, _settings));
        }

        public object Deserialize(byte[] data)
        {
            if (data == null)
            {
                return null;
            }
            return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data), _settings);
        }
    }
}

假设此类在名为 MyCompanyDll 的程序集中定义,你可以设置参数 redisSerializerType 来使用该类:Assuming this class is defined in an assembly with name MyCompanyDll, you can set the parameter redisSerializerType to use it:

<sessionState mode="Custom" customProvider="MySessionStateStore">
    <providers>
        <add type = "Microsoft.Web.Redis.RedisSessionStateProvider"
             name = "MySessionStateStore"
             redisSerializerType = "MyCompany.Redis.JsonSerializer,MyCompanyDll"
             ... />
    </providers>
</sessionState>

输出缓存指令Output cache directive

将 OutputCache 指令添加到希望为其缓存输出的每个页面中。Add an OutputCache directive to each page for which you wish to cache the output.

<%@ OutputCache Duration="60" VaryByParam="*" %>

在上例中,缓存的页面数据可在缓存中保留 60 秒,并且为每个参数组合缓存不同版本的页面。In the previous example, the cached page data remains in the cache for 60 seconds, and a different version of the page is cached for each parameter combination. 有关 OutputCache 指令的详细信息,请参阅 @OutputCacheFor more information about the OutputCache directive, see @OutputCache.

执行这些步骤后,应用程序已配置为使用 Redis 输出缓存提供程序。Once these steps are performed, your application is configured to use the Redis Output Cache Provider.

后续步骤Next steps

了解 Azure Redis 缓存的 ASP.NET 会话状态提供程序Check out the ASP.NET Session State Provider for Azure Cache for Redis.