Windows Server AppFabric 1.0是否存在asp.net输出缓存提供程序?
答案 0 :(得分:2)
没有。但是因为输出缓存在ASP.NET 4.0中是可插入的(使用提供者模型),所以您可以自己编写。
要创建新的输出缓存提供程序,您需要继承System.Web.Caching.OutputCacheProvider
,您需要引用System.Web
和System.Configuration
。
然后,它主要是覆盖基础提供程序中的四种方法,Add,Get,Remove和Set。
由于您的网站可能会获得相当多的点击量,您肯定希望为DataCacheFactory使用Singleton,此代码使用Jon Skeet's singleton pattern(假设我已正确理解它)。
using System;
using System.Web.Caching;
using Microsoft.ApplicationServer.Caching;
namespace AppFabricOutputCache
{
public sealed class AppFabricOutputCacheProvider : OutputCacheProvider
{
private static readonly AppFabricOutputCacheProvider instance = new AppFabricOutputCacheProvider();
private DataCacheFactory factory;
private DataCache cache;
static AppFabricOutputCacheProvider()
{ }
private AppFabricOutputCacheProvider()
{
// Constructor - new up the factory and get a reference to the cache based
// on a setting in web.config
factory = new DataCacheFactory();
cache = factory.GetCache(System.Web.Configuration.WebConfigurationManager.AppSettings["OutputCacheName"]);
}
public static AppFabricOutputCacheProvider Instance
{
get { return instance; }
}
public override object Add(string key, object entry, DateTime utcExpiry)
{
// Add an object into the cache.
// Slight disparity here in that we're passed an absolute expiry but AppFabric wants
// a TimeSpan. Subtract Now from the expiry we get passed to create the TimeSpan
cache.Add(key, entry, utcExpiry - DateTime.UtcNow);
}
public override object Get(string key)
{
return cache.Get(key);
}
public override void Remove(string key)
{
cache.Remove(key);
}
public override void Set(string key, object entry, DateTime utcExpiry)
{
// Set here means 'add it if it doesn't exist, update it if it does'
// We can do this by using the AppFabric Put method
cache.Put(key, entry, utcExpiry - DateTime.UtcNow);
}
}
}
编写完成后,需要配置应用程序以在web.config中使用它:
<system.web>
<caching>
<outputCache defaultProvider="AppFabricOutputCache">
<providers>
<add name="AppFabricOutputCache" type="AppFabricOutputCache, AppFabricOutputCacheProvider" />
</providers>
</outputCache>
</caching>
</system.web>
MSDN: OutputCacheProvider
ScottGu's blog on creating OutputCacheProviders