萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> 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<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);

  }

copyright © 萬盛學電腦網 all rights reserved