最近在开始一个微信开发,发现微信的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 }