在C#ASP.net应用程序中缓存数据时,有没有人建议哪种方法更好?
我目前正在使用两种方法的组合,一些数据(列表,字典,通常的特定于域的信息)直接放入缓存并在需要时装箱,并且一些数据保存在globaldata类中,并且通过该类检索(即GlobalData类被缓存,它的属性是实际数据)。
这两种方法是否更可取?
我觉得从并发的角度来看,单独缓存每个项目会更加明智,但是从长远来看,它会创建更多的工作,其中包含更多的功能,这些功能完全处理从数据库中的缓存位置获取数据实用类。
建议将不胜感激。
答案 0 :(得分:8)
通常,缓存的性能比底层源(例如DB)好得多,因此缓存的性能不是问题。主要目标是获得尽可能高的缓存命中率(除非您正在大规模开发,因为这样才能获得优化缓存的成果)。
为了实现这一点,我通常会尽可能让开发人员尽可能直接使用缓存(这样我们就不会因为开发人员懒得使用缓存而错过任何缓存命中的机会)。在某些项目中,我们使用了Microsoft企业库中提供的CacheHandler的修改版本。
使用CacheHandler(使用Policy Injection),您可以通过向其添加属性轻松地使方法“可缓存”。例如:
[CacheHandler(0, 30, 0)]
public Object GetData(Object input)
{
}
会使对该方法的所有调用都缓存30分钟。所有调用都根据输入数据和方法名称获取一个唯一的缓存键,因此如果您使用不同的输入调用该方法两次,它将不会被缓存,但如果您在输出相同的时间间隔内调用它> 1次,则该方法只执行一次。
我们的修改版本如下所示:
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace Middleware.Cache
{
/// <summary>
/// An <see cref="ICallHandler"/> that implements caching of the return values of
/// methods. This handler stores the return value in the ASP.NET cache or the Items object of the current request.
/// </summary>
[ConfigurationElementType(typeof (CacheHandler)), Synchronization]
public class CacheHandler : ICallHandler
{
/// <summary>
/// The default expiration time for the cached entries: 5 minutes
/// </summary>
public static readonly TimeSpan DefaultExpirationTime = new TimeSpan(0, 5, 0);
private readonly object cachedData;
private readonly DefaultCacheKeyGenerator keyGenerator;
private readonly bool storeOnlyForThisRequest = true;
private TimeSpan expirationTime;
private GetNextHandlerDelegate getNext;
private IMethodInvocation input;
public CacheHandler(TimeSpan expirationTime, bool storeOnlyForThisRequest)
{
keyGenerator = new DefaultCacheKeyGenerator();
this.expirationTime = expirationTime;
this.storeOnlyForThisRequest = storeOnlyForThisRequest;
}
/// <summary>
/// This constructor is used when we wrap cached data in a CacheHandler so that
/// we can reload the object after it has been removed from the cache.
/// </summary>
/// <param name="expirationTime"></param>
/// <param name="storeOnlyForThisRequest"></param>
/// <param name="input"></param>
/// <param name="getNext"></param>
/// <param name="cachedData"></param>
public CacheHandler(TimeSpan expirationTime, bool storeOnlyForThisRequest,
IMethodInvocation input, GetNextHandlerDelegate getNext,
object cachedData)
: this(expirationTime, storeOnlyForThisRequest)
{
this.input = input;
this.getNext = getNext;
this.cachedData = cachedData;
}
/// <summary>
/// Gets or sets the expiration time for cache data.
/// </summary>
/// <value>The expiration time.</value>
public TimeSpan ExpirationTime
{
get { return expirationTime; }
set { expirationTime = value; }
}
#region ICallHandler Members
/// <summary>
/// Implements the caching behavior of this handler.
/// </summary>
/// <param name="input"><see cref="IMethodInvocation"/> object describing the current call.</param>
/// <param name="getNext">delegate used to get the next handler in the current pipeline.</param>
/// <returns>Return value from target method, or cached result if previous inputs have been seen.</returns>
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
lock (input.MethodBase)
{
this.input = input;
this.getNext = getNext;
return loadUsingCache();
}
}
public int Order
{
get { return 0; }
set { }
}
#endregion
private IMethodReturn loadUsingCache()
{
//We need to synchronize calls to the CacheHandler on method level
//to prevent duplicate calls to methods that could be cached.
lock (input.MethodBase)
{
if (TargetMethodReturnsVoid(input) || HttpContext.Current == null)
{
return getNext()(input, getNext);
}
var inputs = new object[input.Inputs.Count];
for (int i = 0; i < inputs.Length; ++i)
{
inputs[i] = input.Inputs[i];
}
string cacheKey = keyGenerator.CreateCacheKey(input.MethodBase, inputs);
object cachedResult = getCachedResult(cacheKey);
if (cachedResult == null)
{
var stopWatch = Stopwatch.StartNew();
var realReturn = getNext()(input, getNext);
stopWatch.Stop();
if (realReturn.Exception == null && realReturn.ReturnValue != null)
{
AddToCache(cacheKey, realReturn.ReturnValue);
}
return realReturn;
}
var cachedReturn = input.CreateMethodReturn(cachedResult, input.Arguments);
return cachedReturn;
}
}
private object getCachedResult(string cacheKey)
{
//When the method uses input that is not serializable
//we cannot create a cache key and can therefore not
//cache the data.
if (cacheKey == null)
{
return null;
}
object cachedValue = !storeOnlyForThisRequest ? HttpRuntime.Cache.Get(cacheKey) : HttpContext.Current.Items[cacheKey];
var cachedValueCast = cachedValue as CacheHandler;
if (cachedValueCast != null)
{
//This is an object that is reloaded when it is being removed.
//It is therefore wrapped in a CacheHandler-object and we must
//unwrap it before returning it.
return cachedValueCast.cachedData;
}
return cachedValue;
}
private static bool TargetMethodReturnsVoid(IMethodInvocation input)
{
var targetMethod = input.MethodBase as MethodInfo;
return targetMethod != null && targetMethod.ReturnType == typeof (void);
}
private void AddToCache(string key, object valueToCache)
{
if (key == null)
{
//When the method uses input that is not serializable
//we cannot create a cache key and can therefore not
//cache the data.
return;
}
if (!storeOnlyForThisRequest)
{
HttpRuntime.Cache.Insert(
key,
valueToCache,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
expirationTime,
CacheItemPriority.Normal, null);
}
else
{
HttpContext.Current.Items[key] = valueToCache;
}
}
}
/// <summary>
/// This interface describes classes that can be used to generate cache key strings
/// for the <see cref="CacheHandler"/>.
/// </summary>
public interface ICacheKeyGenerator
{
/// <summary>
/// Creates a cache key for the given method and set of input arguments.
/// </summary>
/// <param name="method">Method being called.</param>
/// <param name="inputs">Input arguments.</param>
/// <returns>A (hopefully) unique string to be used as a cache key.</returns>
string CreateCacheKey(MethodBase method, object[] inputs);
}
/// <summary>
/// The default <see cref="ICacheKeyGenerator"/> used by the <see cref="CacheHandler"/>.
/// </summary>
public class DefaultCacheKeyGenerator : ICacheKeyGenerator
{
private readonly LosFormatter serializer = new LosFormatter(false, "");
#region ICacheKeyGenerator Members
/// <summary>
/// Create a cache key for the given method and set of input arguments.
/// </summary>
/// <param name="method">Method being called.</param>
/// <param name="inputs">Input arguments.</param>
/// <returns>A (hopefully) unique string to be used as a cache key.</returns>
public string CreateCacheKey(MethodBase method, params object[] inputs)
{
try
{
var sb = new StringBuilder();
if (method.DeclaringType != null)
{
sb.Append(method.DeclaringType.FullName);
}
sb.Append(':');
sb.Append(method.Name);
TextWriter writer = new StringWriter(sb);
if (inputs != null)
{
foreach (var input in inputs)
{
sb.Append(':');
if (input != null)
{
//Diffrerent instances of DateTime which represents the same value
//sometimes serialize differently due to some internal variables which are different.
//We therefore serialize it using Ticks instead. instead.
var inputDateTime = input as DateTime?;
if (inputDateTime.HasValue)
{
sb.Append(inputDateTime.Value.Ticks);
}
else
{
//Serialize the input and write it to the key StringBuilder.
serializer.Serialize(writer, input);
}
}
}
}
return sb.ToString();
}
catch
{
//Something went wrong when generating the key (probably an input-value was not serializble.
//Return a null key.
return null;
}
}
#endregion
}
}
微软最值得赞扬的是这段代码。我们只在请求级别添加了缓存等内容,而不是跨越请求(比您想象的更有用)并修复了一些错误(例如,将相同的DateTime对象序列化为不同的值)。
答案 1 :(得分:3)
您需要在什么条件下使缓存无效?应该存储对象,以便在它们无效时重新填充缓存只需要重新缓存失效的项目。
例如,如果您已缓存,则说明一个Customer对象,其中包含订单的交付详细信息以及购物篮。使购物篮无效,因为他们添加或删除了一个项目也需要不必要地重新填充交付细节。
(注意:这是一个很好的例子,我并不主张这只是为了证明这个原则,而我今天的想象力有点偏差。)
答案 2 :(得分:2)
两个世界中最好的(最糟糕的?)怎么样?
让globaldata
类在内部管理所有缓存访问。您的其余代码可以只使用globaldata
,这意味着它根本不需要缓存感知。
您可以通过更新globaldata
将更改缓存实现更改为/,而其他代码将不知道或不关心内部发生的事情。
答案 3 :(得分:2)
Ed,我认为这些列表和词典包含几乎静态的数据,到期的可能性很小。然后有频繁命中的数据,但也会更频繁地更改,所以你使用HttpRuntime缓存来缓存它。
现在,您应该考虑所有数据以及不同类型之间的所有依赖关系。如果您在逻辑上发现HttpRuntime缓存数据在某种程度上依赖于您的GlobalData项目,您应该将其移动到缓存中并在那里设置适当的依赖项,这样您将受益于“级联到期”。
即使你使用自定义缓存机制,你仍然必须提供所有同步,所以你不会通过避免另一个来节省。
如果您需要(预先订购)频率变化非常低的项目列表,您仍然可以使用HttpRuntime缓存来实现。因此,您只需缓存一个字典,然后使用它来列出您的项目,或者使用自定义键进行索引和访问。
答案 4 :(得分:1)
在构建缓存策略时要考虑的不仅仅是这些。将您的缓存存储看作是您的内存数据库。因此,请仔细处理存储在其中的每种类型的依赖项和到期策略。你用于缓存的内容并不重要(system.web,其他商业解决方案,滚动你自己......)。
我尝试集中它,并使用某种可插拔架构。让您的数据使用者通过公共API(公开它的抽象缓存)访问它,并在运行时插入缓存层(比如说asp.net缓存)。
在缓存数据时应该采用自顶向下的方法来避免任何类型的数据完整性问题(如我所说的那样适当的依赖性),然后注意提供同步。