asp.net中缓存介绍(一)
今天学缓存了
整页缓存技术
<% OutputCache
* Duration=”
*/VaryByParam=”id,name” 参数传递值缓存
*/ VarByControl=”none” 服务控件ID缓存
Location=”any ” 缓存项的存储位置(Any,Client,Downstream(代理服务器),None,Server,ServerAndClient)
VaryByCustom=”whether” 自定义缓存要求 global.asax中定义变动
%>
Global.asax
|
public override string GetVaryByCustomString(HttpContext context, string custom) { if (custom == "whether") { return DateTime.Now.Minute.ToString(); } return base.GetVaryByCustomString(context, custom); } 此方法回去比较两次的值,当不同的时候会缓存过期,重新向服务器发送请求 |
页面部分缓存优化记录
只有剩余票数才支持不缓存,每次都访问数据库
在后台得提供一个带(HttpContext contect)的方法 返回值string 的委托方法签名,在里面写查询数据库信息的代码.
委托签名 public delegate string HttpResponseSubstitutionCallback(HttpContext context);
|
<asp:Substitution ID="Substitution2" runat="server" MethodName="GetMeTable"/> |
|
protected static string GetMeTable(HttpContext context) { DataTable dt = GetTicketsDataTable("2"); return dt.Rows[0]["num"].ToString(); } |
应用程序缓存 (针对于一些文件数据修改时,触发缓存过期,重新读取数据)
Cache 命名空间的引用 using System.Web.Caching;
S protected IList<string> GetStudents()
{
IList<string> students = null;
if (Cache["Students"] != null)
{
students = (IList<string>)Cache["Students"];
}
else
{
XmlDocument xmldoc = new XmlDocument();
string path = Server.MapPath("FileCacheDep.xml");
xmldoc.Load(path);
students = new List<string>();
foreach (XmlNode node in xmldoc.DocumentElement.ChildNodes)
{
students.Add(node.InnerText);
}
System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(path);
System.Web.Caching.CacheItemRemovedCallback onRemove = new System.Web.Caching.CacheItemRemovedCallback(this.OnRemove);
Cache.Add("Students", students, dep, DateTime.MaxValue, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, onRemove);
}
return students;
}
|
public CacheDependency dependencies, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback ) key 用于引用该项的缓存键。 value 要添加到缓存的项。 dependencies 该项的文件依赖项或缓存键依赖项。当任何依赖项更改时,该对象即无效,并从缓存中移除。如果没有依赖项,则此参数包含 空引用(在 Visual Basic 中为 Nothing)。 absoluteExpiration 所添加对象将过期并被从缓存中移除的时间。如果使用可调过期,则 absoluteExpiration 参数必须为 NoAbsoluteExpiration。 slidingExpiration 最后一次访问所添加对象时与该对象过期时之间的时间间隔。如果该值等效于 20 分钟,则对象在最后一次被访问 20 分钟之后将过期并从缓存中移除。如果使用绝对过期,则 slidingExpiration 参数必须为 NoSlidingExpiration。 priority 对象的相对成本,由 CacheItemPriority 枚举表示。缓存在退出对象时使用该值;具有较低成本的对象在具有较高成本的对象之前被从缓存移除。 onRemoveCallback 在从缓存中移除对象时所调用的委托(如果提供)。当从缓存中删除应用程序的对象时,可使用它来通知应用程序。 public delegate CacheItemRemovedReason reason ) public enum CacheItemPriority
|
Insert methor
浙公网安备 33010602011771号