CacheManage.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Web.Caching;
  5. using System.Threading;
  6. namespace Ant.ORM.Cache
  7. {
  8. /// <summary>
  9. /// 全局缓存类
  10. /// </summary>
  11. /// <example><code>
  12. /// 使用示例:
  13. /// 实例化: CacheManage cache=CacheManage.Instance;
  14. /// 添加: cache.Add("路过秋天",new MDataTable);
  15. /// 判断: if(cache.Contains("路过秋天"))
  16. /// {
  17. /// 获取: MDataTable table=cache.Get("路过秋天") as MDataTable;
  18. /// }
  19. /// </code></example>
  20. public class CacheManage
  21. {
  22. private readonly System.Web.HttpContext H = new System.Web.HttpContext(new System.Web.HttpRequest("Null.File", "http://cyq1162.cnblogs.com", String.Empty), new System.Web.HttpResponse(null));
  23. private System.Web.Caching.Cache theCache = null;
  24. private Dictionary<string, CacheDependencyInfo> cacheState = new Dictionary<string, CacheDependencyInfo>();
  25. private DateTime workTime;
  26. /// <summary>
  27. /// 缓存信息
  28. /// </summary>
  29. public Dictionary<string, CacheDependencyInfo> CacheInfo
  30. {
  31. get
  32. {
  33. return cacheState;
  34. }
  35. }
  36. private CacheManage()
  37. {
  38. theCache = H.Cache;
  39. Thread thread = new Thread(new ThreadStart(ClearState));
  40. thread.IsBackground = true;
  41. thread.Start();
  42. workTime = DateTime.Now.AddMinutes(5);
  43. }
  44. private void ClearState()
  45. {
  46. List<string> removeKeys = new List<string>();
  47. while (true)
  48. {
  49. try
  50. {
  51. Thread.Sleep(5 * 60 * 1000);//五分钟休眠时间
  52. if (theCache.Count != cacheState.Count)//准备同步
  53. {
  54. foreach (KeyValuePair<string, CacheDependencyInfo> item in cacheState)
  55. {
  56. if ((item.Value.CreaeTime.AddMinutes(4) < DateTime.Now && item.Value.CallCount < 2) || //缓存调用次数太少
  57. item.Value.CreaeTime.AddMinutes(item.Value.CacheMinutes) < DateTime.Now)//清过期cacheState进行同步
  58. {
  59. if (!removeKeys.Contains(item.Key))
  60. {
  61. removeKeys.Add(item.Key);
  62. }
  63. }
  64. }
  65. foreach (string key in removeKeys)
  66. {
  67. Remove(key);//移除
  68. }
  69. clearCount = removeKeys.Count;
  70. removeKeys.Clear();
  71. }
  72. workTime = DateTime.Now.AddMinutes(5);
  73. }
  74. catch
  75. {
  76. System.Threading.Thread.Sleep(TimeSpan.FromHours(1));
  77. }
  78. }
  79. }
  80. private int errorCount = 0;//缓存捕异常次数
  81. private int clearCount = 0;//清除的缓存数
  82. /// <summary>
  83. /// 缓存工作信息
  84. /// </summary>
  85. public string WorkInfo
  86. {
  87. get
  88. {
  89. return string.Format("try catch error:{0}(times)--clear count:{1}--next clear work time at:{2}", errorCount, clearCount, workTime);
  90. }
  91. }
  92. /// <summary>
  93. /// 获和缓存总数
  94. /// </summary>
  95. public int Count
  96. {
  97. get
  98. {
  99. return theCache == null ? 0 : theCache.Count;
  100. }
  101. }
  102. /// <summary>
  103. /// 返回唯一实例
  104. /// </summary>
  105. public static CacheManage Instance
  106. {
  107. get
  108. {
  109. return Shell.instance;
  110. }
  111. }
  112. class Shell
  113. {
  114. internal static readonly CacheManage instance = new CacheManage();
  115. }
  116. /// <summary>
  117. /// 还可用的缓存百分比
  118. /// </summary>
  119. public long RemainMemoryPercentage
  120. {
  121. get
  122. {
  123. return theCache.EffectivePercentagePhysicalMemoryLimit;
  124. }
  125. }
  126. /// <summary>
  127. /// 还可用的缓存字节数
  128. /// </summary>
  129. public long RemainMemoryBytes
  130. {
  131. get
  132. {
  133. return theCache.EffectivePrivateBytesLimit;
  134. }
  135. }
  136. /// <summary>
  137. /// 获得一个Cache对象
  138. /// </summary>
  139. /// <param name="key">标识</param>
  140. /// <returns></returns>
  141. public object Get(string key)
  142. {
  143. if (Contains(key))
  144. {
  145. try
  146. {
  147. cacheState[key].CallCount++;
  148. }
  149. catch
  150. {
  151. errorCount++;
  152. }
  153. return theCache[key];
  154. }
  155. return null;
  156. }
  157. /// <summary>
  158. /// 是否存在缓存
  159. /// </summary>
  160. /// <param name="key">标识</param>
  161. /// <returns></returns>
  162. public bool Contains(string key)
  163. {
  164. if (theCache[key] != null)
  165. {
  166. return true;
  167. }
  168. else
  169. {
  170. if (cacheState.ContainsKey(key))
  171. {
  172. try
  173. {
  174. cacheState.Remove(key);
  175. }
  176. catch
  177. {
  178. errorCount++;
  179. }
  180. }
  181. return false;
  182. }
  183. }
  184. /// <summary>
  185. /// 添加一个Cache对象
  186. /// </summary>
  187. /// <param name="key">标识</param>
  188. /// <param name="value">对象值</param>
  189. public void Add(string key, object value)
  190. {
  191. Add(key, value, null, 0);
  192. }
  193. public void Add(string key, object value, string filePath)
  194. {
  195. Add(key, value, filePath, 0);//再插入Cache
  196. }
  197. public void Add(string key, object value, string filePath, double cacheTimeMinutes)
  198. {
  199. if (Contains(key))
  200. {
  201. Remove(key);
  202. }
  203. Insert(key, value, filePath, cacheTimeMinutes);//再插入Cache
  204. }
  205. /// <summary>
  206. /// 缓存设置:有则更新,无则添加
  207. /// </summary>
  208. /// <param name="key"></param>
  209. /// <param name="value"></param>
  210. public void Set(string key, object value)
  211. {
  212. if (Contains(key))
  213. {
  214. theCache[key] = value;
  215. }
  216. else
  217. {
  218. Insert(key, value, null, 0);//再插入Cache
  219. }
  220. }
  221. /// <summary>
  222. /// 更新缓存,缓存存在则更更新,不存在则跳过
  223. /// </summary>
  224. public void Update(string key, object value)
  225. {
  226. if (Contains(key))
  227. {
  228. theCache[key] = value;
  229. }
  230. }
  231. /// <summary>
  232. /// 相对底层Cache添加方法,添加一个Cache请用Add方法
  233. /// </summary>
  234. /// <param name="key">标识</param>
  235. /// <param name="value">对象值</param>
  236. /// <param name="filePath">文件依赖路径</param>
  237. /// <param name="cacheTimeMinutes">缓存分钟数</param>
  238. private void Insert(string key, object value, string filePath, double cacheTimeMinutes)
  239. {
  240. CacheDependency theCacheDependency = null;
  241. if (!string.IsNullOrEmpty(filePath))
  242. {
  243. theCacheDependency = new CacheDependency(filePath);
  244. }
  245. double cacheTime = cacheTimeMinutes;
  246. if (cacheTimeMinutes == 0)
  247. {
  248. cacheTime = 30;
  249. }
  250. theCache.Insert(key, value == null ? string.Empty : value, theCacheDependency, DateTime.Now.AddMinutes(cacheTime), TimeSpan.Zero, CacheItemPriority.Default, null);
  251. CacheDependencyInfo info = new CacheDependencyInfo(theCacheDependency, cacheTime);
  252. if (cacheState.ContainsKey(key))
  253. {
  254. cacheState[key] = info;
  255. }
  256. else
  257. {
  258. try
  259. {
  260. cacheState.Add(key, info);
  261. }
  262. catch { }
  263. }
  264. }
  265. /// <summary>
  266. /// 删除一个Cache对象
  267. /// </summary>
  268. /// <param name="key">标识</param>
  269. public void Remove(string key)
  270. {
  271. if (Contains(key))//检测存在时中会自动清除cacheState
  272. {
  273. try
  274. {
  275. theCache.Remove(key);
  276. cacheState.Remove(key);
  277. }
  278. catch
  279. {
  280. errorCount++;
  281. }
  282. }
  283. }
  284. /// <summary>
  285. /// 清除所有缓存
  286. /// </summary>
  287. public void Clear()
  288. {
  289. try
  290. {
  291. foreach (KeyValuePair<string, CacheDependencyInfo> item in cacheState)
  292. {
  293. theCache.Remove(item.Key);
  294. }
  295. cacheState.Clear();
  296. }
  297. catch
  298. {
  299. errorCount++;
  300. }
  301. }
  302. /// <summary>
  303. /// 用户手动设置缓存对象已更改
  304. /// </summary>
  305. /// <param name="key"></param>
  306. /// <param name="change"></param>
  307. public void SetChange(string key, bool change)
  308. {
  309. if (cacheState.ContainsKey(key) && Contains(key))
  310. {
  311. CacheDependencyInfo info = cacheState[key];
  312. if (info != null)
  313. {
  314. info.UserSetChange(change);
  315. }
  316. }
  317. else
  318. {
  319. Add("Ant.ORM.Cache:Temp_" + key, change, null, 0.1);//缓存失效时,产生6秒的key缓冲
  320. }
  321. }
  322. /// <summary>
  323. /// 获取缓存对象是否已被用户手动设置更改
  324. /// </summary>
  325. /// <param name="key"></param>
  326. /// <returns></returns>
  327. public bool GetHasChanged(string key)
  328. {
  329. if (cacheState.ContainsKey(key) && Contains(key))
  330. {
  331. CacheDependencyInfo info = cacheState[key];
  332. if (info != null)
  333. {
  334. return info.IsChanged ? false : info.UserChange;
  335. }
  336. }
  337. else if (Contains("Ant.ORM.Cache:Temp_" + key))
  338. {
  339. return (bool)theCache.Get("Ant.ORM.Cache:Temp_" + key);
  340. }
  341. return false;
  342. }
  343. }
  344. /// <summary>
  345. /// 缓存依赖信息
  346. /// </summary>
  347. public class CacheDependencyInfo
  348. {
  349. public int CallCount = 0;
  350. /// <summary>
  351. /// 缓存产生的时间
  352. /// </summary>
  353. public DateTime CreaeTime;
  354. /// <summary>
  355. /// 缓存多少分钟
  356. /// </summary>
  357. public Double CacheMinutes = 0;
  358. DateTime CacheChangeTime = DateTime.MinValue;
  359. CacheDependency FileDependency = null;
  360. public CacheDependencyInfo(CacheDependency dependency, double cacheMinutes)
  361. {
  362. if (dependency != null)
  363. {
  364. FileDependency = dependency;
  365. CacheChangeTime = FileDependency.UtcLastModified;
  366. }
  367. CreaeTime = DateTime.Now;
  368. CacheMinutes = cacheMinutes;
  369. }
  370. /// <summary>
  371. /// 系统文件依赖是否发生改变
  372. /// </summary>
  373. public bool IsChanged
  374. {
  375. get
  376. {
  377. if (FileDependency != null && (FileDependency.HasChanged || CacheChangeTime != FileDependency.UtcLastModified))
  378. {
  379. CacheChangeTime = FileDependency.UtcLastModified;
  380. return true;
  381. }
  382. return false;
  383. }
  384. }
  385. internal bool UserChange = false;
  386. public void UserSetChange(bool change)
  387. {
  388. UserChange = IsChanged ? false : change;
  389. }
  390. }
  391. }