缓存是个啥?以及为啥要用缓存就不废话了,主要是从实用角度讲下怎么用
1.先添加对Microsoft.Practices.EnterpriseLibrary.Caching.dll的引用
2.修改web.config文件,注意高度部分
...
...
type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral"
name="Cache Manager" />
...
3.使用缓存,见下面的代码,关键地方都加了注释
using System;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
namespace CacheTest
{
///
/// 定义要缓存的实体类
///
public class MyData
{
public string Name { set; get; }
public int Age { set; get; }
public string Color { set; get; }
}
public partial class _Default : System.Web.UI.Page
{
const string KEYNAME = "myDate";//缓存的键值
ICacheManager cacheManager;
protected void Page_Load(object sender, EventArgs e)
{
cacheManager = CacheFactory.GetCacheManager();//实例化ICachemanager
}
protected void btnWrite_Click(object sender, EventArgs e)
{
//生成要缓存的数据(实际开发中可以是从数据库查询出来的数据)
List
new MyData(){ Age=1, Color="Yellow", Name="China"},
new MyData{ Age=2,Color="Black",Name="USA"}
};
AbsoluteTime _ExpireTime = new AbsoluteTime(DateTime.Now.AddSeconds(30));//指定30秒后过期
cacheManager.Add(KEYNAME, _list, CacheItemPriority.Normal, null, _ExpireTime);//加入缓存
Response.Write("Cache写入完成," + DateTime.Now.ToString());
}
protected void btnRead_Click(object sender, EventArgs e)
{
this.R1.DataSource = GetCacheData();
this.R1.DataBind();
Response.Write("Cache加载完成," + DateTime.Now.ToString());
}
///
/// 获取缓存数据
///
///
public List
{
List
if (null == _cacheData)//记得一定要加此判断(因为缓存可能过期)
{
//如果缓存数据为空,则重新生成数据,并加入缓存(为检测效果,特地把Color与Name前加了一个"New")
_cacheData = new List
new MyData(){ Age=1, Color="New Yellow", Name="New China"},
new MyData{ Age=2,Color="New Black",Name="New USA"}
};
AbsoluteTime _ExpireTime = new AbsoluteTime(DateTime.Now.AddSeconds(30));//指定30秒后过期
cacheManager.Add(KEYNAME, _cacheData, CacheItemPriority.Normal, null, _ExpireTime);
}
return _cacheData;
}
}
}
前端页面很简单
html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

值得一提的是,缓存是"全局"性质的,也就是说在一个页面写入了缓存,另一个页面也可以读取(当然:前提是缓存未过期的情况下),我们可以利用这个特性把网站中经常使用的数据(比如一些基础数据)缓存起来,其它要用的地方直接从缓存读取,能有效减少对数据库的访问。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/756/viewspace-2801271/ ,如需转载,请注明出处,否则将追究法律责任。