緩存有很多種,用的最普遍的可能就是內存緩存了。內存緩存的實現方式也有很多種,比如用靜態變量,比如用Cache,但這些方式只針對單一緩存變量,每個緩存變量都要重新寫一套方法,無法實現通用。這裡提供一種通用的內存緩存組件,不用再為每個緩存做實現了。
話不多說,先上代碼:
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.Utility
10 {
11 /// <summary>
12 /// 通用緩存組件
13 /// </summary>
14 public class CacheHelper
15 {
16 /// <summary>
17 /// 獲取緩存對象
18 /// </summary>
19 /// <typeparam name="T">緩存實體對象</typeparam>
20 /// <param name="dele">實體數據獲取方法</param>
21 /// <param name="cacheKey">緩存關鍵字</param>
22 /// <param name="cacheDuration">緩存時間(分鐘)</param>
23 /// <param name="objs">實體數據獲取參數</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 // 執行實體數據獲取方法
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、緩存組件方法接收一個獲取原始數據方法委托,一個緩存key,一個緩存過期時間,以及獲取原始數據方法參數;
2、緩存使用HttpRuntime.Cache實現,這是.net自帶緩存組件,使用絕對緩存(當然根據需要也可以改成滑動緩存);
3、方法先從緩存獲取數據,緩存未取到數據,執行原始數據方法委托,獲取數據,並添加入緩存。
使用示例:
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 CacheHelperTest
13 {
14 /// <summary>
15 /// 測試方法
16 /// </summary>
17 public void Test()
18 {
19 // 獲取數據
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("獲取數據成功!");
25 }
26 }
27
28 /// <summary>
29 /// 獲取原始數據
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 }
總結:
1、該緩存組件可以擴展,獲取原始數據方法可以是調用服務,可以是發送Http請求等;
2、緩存的方式也可以擴展,將HttpRuntime.Cache替換成Redis或其他緩存,甚至可以封裝一個多級緩存方式的復雜緩存,這裡讓使用緩存的方式更方便。