Blog中的Cache应用

2006年10月19日 9:50 上午  |  分类:Develop
Blog昨天已给一份下一秒,并在本地调试成功。
通过我在本地做的NUnit测试,表明未出现程序上的错误。
Blog的主要页面均做了5分钟的Cache,所以大家现在看到的内容未必就是最新的。
Blog在朋友的一台服务器上,放在这里的目的主要用来做一个测试。因为前段时间放在剣气那里,一直出错,而且基本上都是SqlException异常,但实际上,blog里未涉及到大量、复杂的数据查询,而且在代码编写上,基本上都是安全的。
刚进后台看了一下站点的所有缓存
 
当前共有18个缓存项,上服务器看到blog所在的w3wp占用内存52M,这是使用缓存的结果。
过二天去掉所有缓存项,实时从数据库查询,再来看看内存占用情况。

列出当前站点所有Cache并清除

2006年09月25日 11:40 上午  |  分类:Develop

Blog经过一次大的修整后
几个页面都采用了Cache机制,并设定了相应的过期时间
这样会加快页面的载入,减少等待的时间

但同时也有一个弊端:无法正确获取最新的记录
如发布一篇日志后,可能不会立即在首页显示出来,必须等缓存过期后,
才会再从数据库查询一次,此时才会看到最新的记录.

有时可能需要立即更新,这里就必须手工清除一下Cache
Cache类有一个Remove方法,但该方法需要提供一个CacheKey,但整个网站的CacheKey我们是无法得知的
只能经过遍历

protected void RemoveAllCache()
{

System.Web.Caching.Cache _cache = HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
ArrayList al = new ArrayList();
while (CacheEnum.MoveNext())
{
al.Add(CacheEnum.Key);
}

foreach (string key in al)
{
_cache.Remove(key);
}
show();
}
//显示所有缓存
void show()
{
string str = "";
IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();

while (CacheEnum.MoveNext())
{
str += "缓存名<b>[" + CacheEnum.Key+"]</b><br />" ;
}
this.Label1.Text = "当前网站总缓存数:" + HttpRuntime.Cache.Count + "<br />"+str;
}

对Cache的疑问

2006年09月6日 12:43 下午  |  分类:Develop

Blog的首页用的是一个Repeater
DataSource来自一个类的某个方法,返回的是一个DataTable
default页面没有做任何的Cache
直接将Repeater绑定到该DataTable然后进行显示
但这样一来在处理一些特殊日志时不大方便,如“隐藏日志”

于是创建一个List泛类型,遍历该DataTable,依次创建一个Document的实体,Add至List中,进行Cache

string _cachekey = "dv_" + _pagesize.ToString();
if (Cache[_cachekey] == null)
{

List<Blog.Model.documents.documents> list = new List<Blog.Model.documents.documents>();
if (dv.Rows.Count > 0)
{
for (int i = 0; i < dv.Rows.Count; i++)
{
Blog.Model.documents.documents doc = new Blog.Model.documents.documents();
doc.author = dv.Rows[i]["author"].ToString();
doc.CateGoryID = (int)dv.Rows[i]["CateGoryID"];
doc.CategoryName = dv.Rows[i]["CategoryName"].ToString();
doc.commont = "";
doc.content = dv.Rows[i]["content"].ToString();
doc.documentid = (int)dv.Rows[i]["documentid"];
doc.DocumentType = "";
doc.editor = "";
doc.EnableComment = (bool)dv.Rows[i]["enablecomment"];
doc.FilePath = "";
doc.guid = "";
doc.hit = (int)dv.Rows[i]["hit"];
doc.Iscommend = (bool)dv.Rows[i]["Iscommend"];
doc.IsTop = (bool)dv.Rows[i]["istop"];
doc.keyword = "";
doc.PublishDate = (DateTime)dv.Rows[i]["PublishDate"];
doc.source = "";
doc.subject = dv.Rows[i]["subject"].ToString();
doc.Tags = global.getTagsByDocumentid(doc.documentid);
doc.url = "";
doc.IsPublish = (bool)dv.Rows[i]["ispublish"];
if (doc.IsPublish == false)
{
doc.subject = "隐藏日志或草稿";
doc.content = "隐藏日志或草稿,暂时无法查看!";
}
list.Add(doc);
}
}
Cache.Insert(_cachekey, list, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null);
}

_rep_body.DataSource = (List< Blog.Model.documents.documents>)Cache[_cachekey];
_rep_body.DataBind();

但实际运行效率却不如做Cache之前的效率
这个问题发生在哪里?
是对List的操作上吗?