在程序中经常需要用到一些内存缓存,每个获取到的数据都需要重新实现一遍缓存处理,代码冗余,基于此,现提供一种通用的内存缓存实现,直接上代码:
/// <summary>
/// 获取缓存对象
/// </summary>
/// <typeparam name="T">缓存实体对象</typeparam>
/// <param name="dele">实体数据获取方法</param>
/// <param name="cacheKey">缓存关键字</param>
/// <param name="cacheDuration">缓存时间(分钟)</param>
/// <param name="objs">实体数据获取参 </param>
/// <returns>参数T </returns>
public static T GetCacheData<T>( Delegate dele, string cacheKey, int cacheDuration, params ob ject [] objs)
{
if ( HttpRuntime.Cache.Get(cacheKey) == null )
{
string assemblyName = dele.Target.GetType().Assembly.FullName;
string typeName = dele.Target.GetType().FullName;
ob ject instance = Assembly.Load(assemblyName).CreateInstance(typeName);
MethodInfo methodInfo = dele.Method;
T result = (T)methodInfo.Invoke(instance, objs);
HttpRuntime.Cache.Add(cacheKey, result, null , Cache.NoAbsoluteExpiration, TimeSpan .FromMinutes(cacheDuration), CacheItemPriority.NotRemovable, null );
}
return (T) HttpRuntime.Cache[cacheKey];
}
使用HttpRuntime.Cache缓存数据,缓存数据不存在,用委托和反射调用业务方法获取业务数据并缓存。使用如下:
string result = CacheHelper.GetCacheData<string>(new Func<string, string>(cacheTest.GetMyData), "one", 5, "test");
附上另一个可能会重载的版本:
public static TResult GetCacheData<T1, T2, TResult>(Func<T1, T2, TResult> func, string cacheKey, int cacheTime, T1 para1, T2 para2)
{
if (HttpRuntime.Cache.Get(cacheKey) == null)
{
Console.WriteLine("未命中缓存");
TResult result = func(para1, para2);
HttpRuntime.Cache.Add(cacheKey, result, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(cacheTime), CacheItemPriority.NotRemovable, null);
return result;
}
Console.WriteLine("命中缓存");
return (TResult)HttpRuntime.Cache.Get(cacheKey);
}