[置顶] 页面缓存,cache,设置缓存过期时间,OutputCache

时间:2022-05-11 06:00:37

页面缓存

方法一:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//缓存有数据
if (Cache["List"] == null)
{
string sql = "select * from [dbo].[sys_user]"; ////没有过期时间
////Cache["List"] = AutoCodeKldder.SqlHelper.ExeccutDataTable(sql);
//Cache.Insert("List", AutoCodeKldder.SqlHelper.ExeccutDataTable(sql)); //带过期时间(15秒)
Cache.Insert("List", AutoCodeKldder.SqlHelper.ExeccutDataTable(sql), null, DateTime.Now.AddSeconds(15), System.Web.Caching.Cache.NoSlidingExpiration);
}
//从缓存拿数据
DataTable data = Cache["List"] as DataTable;
StringBuilder str = new StringBuilder();
if (data.Rows.Count > 0)
{
foreach (DataRow row in data.Rows)
{
string name = row["loginId"].ToString().Trim();
str.Append(name + "<br />");
}
}
Response.Write(str.ToString().Trim());
}
}

方法二:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//前台有<%@ OutputCache Duration="15" VaryByParam="none" %>标记 页面缓存15秒
//Duration 以秒为单位的缓存时间
//VaryByParam 区分参数 带参数的为: VaryByParam="id" or VaryByParam="id;name" or VaryByParam="*"
string sql = "select * from [dbo].[sys_user]";
DataTable data = AutoCodeKldder.SqlHelper.ExeccutDataTable(sql);
StringBuilder str = new StringBuilder();
if (data.Rows.Count > 0)
{
foreach (DataRow row in data.Rows)
{
string name = row["loginId"].ToString().Trim();
str.Append(name + "<br />");
}
}
Response.Write(str.ToString().Trim());
Response.Write(DateTime.Now.ToString());
}
}

。前台有<%@ OutputCache Duration="15" VaryByParam="none" %>标记 页面缓存15秒

。Duration 以秒为单位的缓存时间

。VaryByParam 区分参数 带参数的为: VaryByParam="id" or VaryByParam="id;name" or VaryByParam="*"