页面缓存
缓存:把数据放到内存里面,下次请求的时候,直接从内存读取数据返回给客户端就可以,不用再去访问数据库或者硬盘,用内存空间换磁盘读取时间。
使用方法:给页面添加<%@ OutputCache Duration="15" VaryByParam="*"%>标签就可以启用缓存,这样整个页面的内容都会被缓存,页面中的ASP.Net代码、数据源在缓存期间都不会被运行,而是直接输出缓存的页面内容,Duration表示缓存时间,以秒巍峨单位,超过这个时间则缓存失败,再次生成以后会再缓存15秒,以此类推。在Page_Load处设置断点、修改数据库数据测试。这个缓存是在服务器缓存的,不是在客户端,因为用HttpWatch还是能看到向服务器提交的请求的,只不过服务器看到有缓存就没有再执行页面类。一般只有看帖、新闻、视频的页面才有缓存,为了能让不同的新闻各自缓存,可以设置VarByParam="id",表示对于相同页面的不同的ID参数进行单独缓存,CRUD的页面没有必要缓存。
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="01PageCacheDemo.aspx.cs" Inherits="ThreeLayerWebDemo._2019_7_12._01PageCacheDemo" %> 2 3 <!DOCTYPE html> 4 <%@ OutputCache Duration="15" VaryByParam="*"%> 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 8 <title></title> 9 </head> 10 <body> 11 <form id="form1" runat="server"> 12 <div> 13 <%=DateTime.Now %> 14 </div> 15 </form> 16 </body> 17 </html>
数据源缓存:
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 if (!IsPostBack) 4 { 5 Response.Write("往缓存写入数据成功!"); 6 //Cache["key"] = DateTime.Now.ToString(); //永不过期 7 //Cache.Remove("key"); //手动删除 8 9 //设置过期时间的缓存 10 //Cache.Insert("key", DateTime.Now.ToString(),null,DateTime.Now.AddSeconds(30),TimeSpan.Zero); 11 12 //设置滑动过期时间 13 Cache.Insert("key", DateTime.Now.ToString(), null, DateTime.MaxValue, new TimeSpan(0, 0, 10)); 14 } 15 else 16 { 17 Response.Write(HttpContext.Current.Cache["key"]); 18 } 19 }

浙公网安备 33010602011771号