緩存有很多種,用的最普遍的可能就是內(nèi)存緩存了。內(nèi)存緩存的實現(xiàn)方式也有很多種,比如用靜態(tài)變量,比如用Cache,但這些方式只針對單一緩存變量,每個緩存變量都要重新寫一套方法,無法實現(xiàn)通用。這里提供一種通用的內(nèi)存緩存組件,不用再為每個緩存做實現(xiàn)了。
話不多說,先上代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Reflection; 5 using System.Text; 6 using System.Web; 7 using System.Web.Caching; 8 9 namespace Loncin.CodeGroup10.Utility10 {11 /// <summary>12 /// 通用緩存組件13 /// </summary>14 public class CacheHelper15 {16 /// <summary>17 /// 獲取緩存對象18 /// </summary>19 /// <typeparam name="T">緩存實體對象</typeparam>20 /// <param name="dele">實體數(shù)據(jù)獲取方法</param>21 /// <param name="cacheKey">緩存關(guān)鍵字</param>22 /// <param name="cacheDuration">緩存時間(分鐘)</param>23 /// <param name="objs">實體數(shù)據(jù)獲取參數(shù)</param>24 /// <returns>返回對象</returns>25 public static T GetCacheData<T>(Delegate dele, string cacheKey, int cacheDuration, params object[] objs)26 {27 // 緩存為空28 if (HttPRuntime.Cache.Get(cacheKey) == null)29 {30 // 執(zhí)行實體數(shù)據(jù)獲取方法31 MethodInfo methodInfo = dele.Method;32 33 T result = (T)methodInfo.Invoke(dele.Target, objs);34 35 if (result != null)36 {37 // 到期時間38 DateTime cacheTime = DateTime.Now.AddMinutes(cacheDuration);39 40 // 添加入緩存41 HttpRuntime.Cache.Add(cacheKey, result, null, cacheTime, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);42 }43 }44 45 return (T)HttpRuntime.Cache[cacheKey];46 }47 }48 }1、緩存組件方法接收一個獲取原始數(shù)據(jù)方法委托,一個緩存key,一個緩存過期時間,以及獲取原始數(shù)據(jù)方法參數(shù);
2、緩存使用HttpRuntime.Cache實現(xiàn),這是.net自帶緩存組件,使用絕對緩存(當然根據(jù)需要也可以改成滑動緩存);
3、方法先從緩存獲取數(shù)據(jù),緩存未取到數(shù)據(jù),執(zhí)行原始數(shù)據(jù)方法委托,獲取數(shù)據(jù),并添加入緩存。
使用示例:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using Loncin.CodeGroup10.Utility; 6 7 namespace Loncin.CodeGroup10.ConsoleTest.Test 8 { 9 /// <summary>10 /// 通用緩存組件測試11 /// </summary>12 public class CacheHelperTest13 {14 /// <summary>15 /// 測試方法16 /// </summary>17 public void Test()18 {19 // 獲取數(shù)據(jù)20 var testData = CacheHelper.GetCacheData<List<int>>(new Func<int, List<int>>(GetTestData), "TestKey", 5, 10);21 22 if (testData != null && testData.Count > 0)23 {24 Console.WriteLine("獲取數(shù)據(jù)成功!");25 }26 }27 28 /// <summary>29 /// 獲取原始數(shù)據(jù)30 /// </summary>31 /// <param name="count"></param>32 /// <returns></returns>33 public List<int> GetTestData(int count)34 {35 var testData = new List<int>();36 for (int i = 0; i < count; i++)37 {38 testData.Add(i);39 }40 41 return testData;42 }43 }44 }總結(jié):
1、該緩存組件可以擴展,獲取原始數(shù)據(jù)方法可以是調(diào)用服務,可以是發(fā)送Http請求等;
2、緩存的方式也可以擴展,將HttpRuntime.Cache替換成Redis或其他緩存,甚至可以封裝一個多級緩存方式的復雜緩存,這里讓使用緩存的方式更方便。
新聞熱點
疑難解答