手机
当前位置:查字典教程网 >编程开发 >编程语言综合 >C#实现简单的通用缓存实现
C#实现简单的通用缓存实现
摘要:在程序中经常需要用到一些内存缓存,每个获取到的数据都需要重新实现一遍缓存处理,代码冗余,基于此,现提供一种通用的内存缓存实现,直接上代码:/...

在程序中经常需要用到一些内存缓存,每个获取到的数据都需要重新实现一遍缓存处理,代码冗余,基于此,现提供一种通用的内存缓存实现,直接上代码:

/// 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( 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.GetCacheDatastring(new Funcstring, string(cacheTest.GetMyData), one, 5, test

附上另一个可能会重载的版本:

public static TResult GetCacheDataT1, T2, TResult(FuncT1, 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);

}

【C#实现简单的通用缓存实现】相关文章:

Ruby实现的最优二叉查找树算法

Ruby实现的最长公共子序列算法

Python实现程序的单一实例用法分析

Ruby实现的矩阵连乘算法

python简单实现基于SSL的IRC bot实例

Ruby实现的合并排序算法

Lua中关系运算符的使用教程

Python实现简单截取中文字符串的方法

C#实现百分比转小数的方法

C#实现把txt文本数据快速读取到excel中

精品推荐
分类导航