Blog中的Cache应用
2006-10-19
列出当前站点所有Cache并清除
2006-09-25Blog经过一次大的修整后
几个页面都采用了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-06Blog的首页用的是一个Repeater
DataSource来自一个类的某个方法,返回的是一个DataTable
default页面没有做任何的Cache
直接将Repeater绑定到该DataTable然后进行显示
但这样一来在处理一些特殊日志时不大方便,如“隐藏日志”
于是创建一个List
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的操作上吗?