System.Web.Caching
System.Web.Caching简单封装类:
1 using System; 2 using System.Collections.Generic; 3 using System.Web.Caching; 4 using System.Web; 5 using System.Collections; 6 7 namespace APP.HttpCache 8 { 9 public class CacheHelper 10 { 11 private static Cache cacheObj = HttpRuntime.Cache; 12 13 ///14 /// 简单key,vlaue写入 15 /// 16 /// 17 /// 18 public static void Insert(string key, object value) 19 { 20 cacheObj.Insert(key, value); 21 } 22 23 /// 24 /// 设置绝对过期时间 25 /// 26 /// 27 /// 28 /// 29 /// 30 public static void Insert(string key, object value, DateTime absoluteExpiration) 31 { 32 cacheObj.Insert(key, value, null, absoluteExpiration, Cache.NoSlidingExpiration); 33 } 34 35 /// 36 /// 设置平滑过期 37 /// 38 /// 39 /// 40 /// 41 public static void Insert(string key, object value, TimeSpan slidingExpiration) 42 { 43 cacheObj.Insert(key, value, null, Cache.NoAbsoluteExpiration, slidingExpiration); 44 } 45 46 /// 47 /// 得到vlaue 48 /// 49 /// 50 /// 51 public static object Get(string key) 52 { 53 return cacheObj.Get(key); 54 } 55 56 /// 57 /// 得到vlaue 58 /// 59 /// 60 /// 61 public static T Get (string key) 62 { 63 var v = cacheObj.Get(key); 64 return v == null ? default(T) : (T)Convert.ChangeType(v, typeof(T)); 65 } 66 67 /// 68 /// 移除key 69 /// 70 /// 71 /// 72 public static void Delete(string key) 73 { 74 cacheObj.Remove(key); 75 } 76 77 /// 78 /// 移除key 79 /// 80 /// 81 /// 82 public static object Remove(string key) 83 { 84 return cacheObj.Remove(key); 85 } 86 87 /// 88 /// 移除key 89 /// 90 /// 91 /// 92 public static T Remove (string key) 93 { 94 var v = cacheObj.Remove(key); 95 return v == null ? default(T) : (T)Convert.ChangeType(v, typeof(T)); 96 } 97 98 /// 99 /// 缓存key数量 100 /// 101 public static int KeyCount 102 { 103 get 104 { 105 return cacheObj.Count; 106 } 107 } 108 109 /// 110 /// 所有key 111 /// 112 public static ArrayList KeyAll() 113 { 114 var arr = new ArrayList(); 115 var item = cacheObj.GetEnumerator(); 116 while (item.MoveNext()) 117 { 118 arr.Add(item.Key); 119 } 120 return arr; 121 } 122 123 /// 124 /// 清空所有缓存 125 /// 126 public static void DeleteAll() 127 { 128 var item = cacheObj.GetEnumerator(); 129 while (item.MoveNext()) 130 { 131 cacheObj.Remove(item.Key.ToString()); 132 } 133 } 134 } 135 }