最近在開始一個微信開發,發現微信的Access_Token獲取每天次數是有限的,然後想到緩存,正好看到微信教程裡面推薦HttpRuntime.Cache緩存就順便看了下。 ...
最近在開始一個微信開發,發現微信的Access_Token獲取每天次數是有限的,然後想到緩存,正好看到微信教程裡面推薦HttpRuntime.Cache緩存就順便看了下。
寫了(Copy)了一個輔助類,目前只包括創建,獲取,及清空
下麵是代碼:
1 using System; 2 using System.Collections; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Web; 6 using System.Web.Caching; 7 8 namespace TEST.Public 9 { 10 public class CacheHelper 11 { 12 13 /// <summary> 14 /// 創建緩存 15 /// </summary> 16 /// <param name="key">緩存的Key</param> 17 /// <param name="value">緩存的數據</param> 18 /// <param name="cacheDependency">依賴項,一般為null</param> 19 /// <param name="dateTime">緩存過期時間</param> 20 /// <param name="timeSpan">設置緩存是不使用過期還是到時間就過期</param> 21 /// <param name="cacheItemPriority">緩存優先順序</param> 22 /// <param name="cacheItemRemovedCallback">回調方法,一般為null</param> 23 /// <returns></returns> 24 public bool CreateCache(string key, object value, CacheDependency cacheDependency, DateTime dateTime, TimeSpan timeSpan, 25 CacheItemPriority cacheItemPriority, CacheItemRemovedCallback cacheItemRemovedCallback) 26 { 27 if (string.IsNullOrEmpty(key) || value == null) 28 { 29 return false; 30 } 31 HttpRuntime.Cache.Insert(key, value, cacheDependency, dateTime, timeSpan, cacheItemPriority, cacheItemRemovedCallback); 32 return true; 33 } 34 35 /// <summary> 36 /// 獲取緩存 37 /// </summary> 38 /// <param name="key"></param> 39 /// <returns></returns> 40 public object GetCache(string key) 41 { 42 return string.IsNullOrEmpty(key) ? null : HttpRuntime.Cache.Get(key); 43 } 44 45 46 /// <summary> 47 /// 移除所有緩存 48 /// </summary> 49 /// <returns></returns> 50 public bool RemoveAll() 51 { 52 IDictionaryEnumerator iDictionaryEnumerator = HttpRuntime.Cache.GetEnumerator(); 53 while (iDictionaryEnumerator.MoveNext()) 54 { 55 HttpRuntime.Cache.Remove(Convert.ToString(iDictionaryEnumerator.Key)); 56 } 57 return true; 58 } 59 } 60 }