博客园  :: 联系 :: 管理

【转】缓存操作类

Posted on 2011-02-24 09:33  独孤雁  阅读(304)  评论(0编辑  收藏  举报
1using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Web.Caching;
5
using System.Web;
6
7
namespace Koyee.Common
8{
9 public class CacheHelp
10 {
11
12 /**//// 简单创建/修改Cache,前提是这个值是字符串形式的
13 /// <summary>
14 /// 简单创建/修改Cache,前提是这个值是字符串形式的
15 /// </summary>
16 /// <param name="strCacheName">Cache名称</param>
17 /// <param name="strValue">Cache值</param>
18 /// <param name="iExpires">有效期,秒数(使用的是当前时间+秒数得到一个绝对到期值)</param>
19 /// <param name="priority">保留优先级,1最不会被清除,6最容易被内存管理清除(1:NotRemovable;2:High;3:AboveNormal;4:Normal;5:BelowNormal;6:Low)</param>
20 public static void Insert(string strCacheName, object strValue, int iExpires, int priority)
21 {
22 //TimeSpan ts = new TimeSpan(0, 0, iExpires);
23 CacheItemPriority cachePriority;
24 switch (priority)
25 {
26 case 6:
27 cachePriority = CacheItemPriority.Low;
28 break;
29 case 5:
30 cachePriority = CacheItemPriority.BelowNormal;
31 break;
32 case 4:
33 cachePriority = CacheItemPriority.Normal;
34 break;
35 case 3:
36 cachePriority = CacheItemPriority.AboveNormal;
37 break;
38 case 2:
39 cachePriority = CacheItemPriority.High;
40 break;
41 case 1:
42 cachePriority = CacheItemPriority.NotRemovable;
43 break;
44 default:
45 cachePriority = CacheItemPriority.Default;
46 break;
47 }
48 HttpContext.Current.Cache.Insert(strCacheName, strValue, null, DateTime.Now.AddHours(iExpires), System.Web.Caching.Cache.NoSlidingExpiration, cachePriority, null);
49 }
50
51 /**//// 简单读书Cache对象的值
52 /// <summary>
53 /// 简单读书Cache对象的值
54 /// </summary>
55 /// <param name="strCacheName">Cache名称</param>
56 /// <returns>Cache字符串值</returns>
57 public static object Get(string strCacheName)
58 {
59 if (HttpContext.Current.Cache[strCacheName] == null)
60 {
61 return null;
62 }
63 return HttpContext.Current.Cache[strCacheName];
64 }
65
66 /**//// 删除Cache对象
67 /// <summary>
68 /// 删除Cache对象
69 /// </summary>
70 /// <param name="strCacheName">Cache名称</param>
71 public static void Del(string strCacheName)
72 {
73 HttpContext.Current.Cache.Remove(strCacheName);
74 }
75
76 }
77}

以上就是缓存操作类,需要声明的一点就是,这里把缓存时间默认为了以小时为单位,这是酷易商城系统决定的。

通过以上静态方法就可以非常方便的进行缓存操作,首先看一下首页商品列表的缓存加载,

调用方法下:

protected void StartLoad(int PageIndex, Repeater rep, string strWhere, string ClassID, string type, int count)
{
string cacheName = listcacheName + type;
if (CacheHelp.Get(cacheName) == null)
{
DataTable data;
//此处为信息查询
CacheHelp.Insert(cacheName, data, 300, 3);//把查询数据输入到缓存中
}
rep.DataSource
= CacheHelp.Get(cacheName) as DataTable;
//设置数据源
rep.DataBind();
}