asp.net 缓存

一:缓存概念,缓存的好处、类型

      概念: 缓存是一种使用空间换取时间的的技术  通俗点说就是将你的数据放在内存里面存储一段时间  在这段时间内  如果你需要这些数据  那么不必要去访问数据库  直接从内存中读取出这些数据即可  

    缓存的好处: 缓存是网站性能优化的中的一种机制 可以有效的缓解数据库方面的压力    比如说  在一分钟内 有1万人访问你“联系我们” 这个页面(如果没有viewstate)  而相对来说 这个页面的内容一般是不需要进行改变的  那我们可以使用缓存 将这个页面的内容缓存起来    在缓存未过期的时间内 直接从缓存中取出你需要的数据即可   这样可以减少访问数据库的压力    

    缓存的类型 :  页面缓存, 数据缓存  

---------------------------------------------------------------------------------------------------------------------------------------------------------------

 二:缓存的处理机制

图解的自我理解

当浏览器第一次给服务器发送一个url请求的时候  会在管道事件中的第15个和第16个之间判断请求页面类的对象是否有实现 OutputCache 命令   如果有 那么会将response里面的数据缓存到服务器的内存中     同时会在响应报文头里面产生一个last-modifine(服务器响应给浏览器的时间)   还有一个Expires   Expries=last-modifine +Duration的值 

在第二次请求的是 同一个url的时候  会将上一次的last-modifine 赋值给 请求报文头里面的If-Modified-Since:   同时 也会产生一个last-modifine  判断浏览器时间是否小于Expires  如果小于 那么久取出缓存  执行完19个管道事件   然后将内容传回给浏览器显示  此时的状态为    304   

如果当前浏览器的时间不小与Expires的时间  那么回执行第8个事件  重新创建页面类的对象    还会在第15  第16个事件中更新缓存数据   执行完19个管道事件后  就将数据返回给服务器 在传回给客户端  此时状态为200 

-------------------------------------------------------------------------------------------------------------------------------------------------------------

缓存的种类

整页缓存   :

             <%@ OutputCache Duration ="10" VaryByParam =“none" %>  

Duration设置缓存的时间   Duration表示的是秒    VarByParam=”None”指定ASP.NET只存储缓存页面的一个拷贝

例如: 将整页的数据缓存10秒

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="P01PageCache.aspx.cs" Inherits="Cache.P01PageCache" %>

<%@ OutputCache Duration="10" VaryByParam="none" %>

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<%=DateTime.Now%>
</form>
</body>
</html>

 

或者将缓存的指令写在配置文件中:  配置在<system.web> 节点下面

<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="ccach" duration="10" varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>

如果在配置文件中写了缓存的配置的节点 那么在前端是不需要在写 OutPutCache 的指令集的

通过参数来改变缓存

       例如:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="P02ByParamsCache.aspx.cs" Inherits="Cache.P02ByParamsCache" %>

<%@ OutputCache Duration="50" VaryByParam="id;name" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=DateTime.Now %>
</div>
</form>
</body>
</html>

  在Duration的时间内 通过更改url:http://localhost:1172/P02ByParamsCache.aspx?id=1&name=jack   中id 和name的值 来更新缓存   

控件缓存

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="P03ByControls.aspx.cs" Inherits="Cache.P03ByControls" %>

 

<%@ OutputCache Duration="10" VaryByParam="none" VaryByControl="DropDownList1" %>

 


<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="" Value="0"></asp:ListItem>
<asp:ListItem Text="" Value="1"></asp:ListItem>
</asp:DropDownList>
</div>
<%=DateTime.Now %>
</form>
</body>
</html>

 

在缓存有效期内,通过更改DropDownList1里面的选项 再刷新页面之后 会获取到更新的数据

自定义控件缓存

首先添加自定义类  然后再里面协商缓存的指令集 和需要缓存的内容

<%@ OutputCache Duration="20" VaryByParam="none" %>
这是自定义控件里面的内容:<%=DateTime.Now %>

然后再.aspx页面中 拖入自定义的控件   页面de顶端会自动生成一个register的指令集

<uc1:WebUserControl1 runat="server" ID="WebUserControl1" />(词自定义控件由外界拖入)
这是控件之外的时间:<%=DateTime.Now %>

产生的Register指令集

<%@ Register Src="~/WebUserControl1.ascx" TagPrefix="uc1" TagName="WebUserControl1" %>

运行这个页面之后 会看到自定义缓存的空间的内容是不会改变的  但是在另外一个DateTime.Now的时间会改变

数据缓存

       相对过期时间:

比如你设置的过期时间是20秒  那么你在这20秒内点击一次(假设当前时间为 14:14:12) 那么过期的时间就是14:14:12+20s=14:14:32  也就是在14:14:32后缓存将会失效     每点击一次 那么久从当前的时间开始计算 在加上Duration的时间  那么就是过期的时间

     绝对过期时间:

 比如你设置的过期的时间是20秒  那么在这20s内  你怎么操作 都是取得是缓存里面的数据 一旦20S超过之后 那么缓存就失效

   文件依赖缓存

 

 protected void Page_Load(object sender, EventArgs e)
        {
            DateTime now;
            //判断当前是否存在缓存
            object obj = HttpRuntime.Cache["time"];

            if (obj == null)
            {
                now = DateTime.Now;
                System.Web.Caching.CacheDependency file = new System.Web.Caching.CacheDependency(Server.MapPath("/1.txt"));
                HttpRuntime.Cache.Add(
                    "time",//缓存的键
                      now,//缓存里面存放的值
                      file,//过期策略
                      System.Web.Caching.Cache.NoAbsoluteExpiration,//绝对过期时间
                      TimeSpan.Zero,//相对过期时间
                      System.Web.Caching.CacheItemPriority.Normal,//缓存的缓存级别
                      null//缓存过期后执行的回调函数
                    );
                obj = HttpRuntime.Cache["time"];
            }
            Response.Write(obj.ToString());
        }

   数据库依赖缓存

   1.0 修改web.config 

<caching>
      <sqlCacheDependency pollTime="1000">
        <databases>
          <add name="tb" connectionStringName="Conn"/>Conn是当前连接数据库节点的名称
        </databases>
      </sqlCacheDependency>
    </caching>

 2.0 使用cmd 创建一个数据库缓存依赖的表

  打开CMD       cd   C:WindowsMicrosoft.NETFrameworkv4.0.30319  跳转到当前目录下面  aspnet_regsql.dll程序集

 然后使用CMD命令

aspnet_regsql -C "data source=127.0.0.1;initial catalog= cachedb;user id=sa;password=123" -ed -et -t "Contents"
 
 cachedb是你当前需要缓存数据所在的数据库  Contents 缓存这个表里面的内容
 
运行这段代码之后会生成一个新的表  其中包含以下字段
 
tableName(创建这个表的缓存)  
notificationCreated:创建的时间  
changeid   
 
3.0 设置缓存的存取方法
  
 public class MgrCache
    {
        //1.0存
        /// <summary>
        /// 相对过期时间
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="obj"></param>
        public static void SetCache(string cacheKey, object obj)
        {
            HttpRuntime.Cache.Add(
               cacheKey,//缓存键
               obj,//
               null,//过期策略
              DateTime.Now.AddDays(1),//绝对过期时间
               TimeSpan.Zero,//绝对过期时间
               CacheItemPriority.Normal,//优先级
               null//回调函数
                );
        }
        /// <summary>
        /// 设置数据库缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="obj"></param>
        /// <param name="sqlDep"></param>
        public static void SetCache(string cacheKey, object obj, SqlCacheDependency sqlDep)
        {
            HttpRuntime.Cache.Add(
               cacheKey,//缓存键
               obj,//
               sqlDep,//过期策略
              System.Web.Caching.Cache.NoAbsoluteExpiration,//绝对过期时间
               TimeSpan.Zero,//相对过期时间
               CacheItemPriority.Normal,//优先级
               null//回调函数
                );
        }


        //2.0取
        public static object GetCache(string cacheKey)
        {
            object obj;
            if (HttpRuntime.Cache[cacheKey] != null)
            {
                obj = HttpRuntime.Cache[cacheKey];
            }
            else
            {
                obj = null;
            }
            return obj;
        }
    }

//4.0 使用

if (HttpRuntime.Cache[Kits.CacheKey] == null)
            {
                //去数据库里面查找联系我们一栏
                ContentsEntity entity = Contents_BLLSub.Get_ContentsEntity(17);
                //给sb赋值
                sb = entity.cnt_content;
                System.Web.Caching.SqlCacheDependency sqlDep = new System.Web.Caching.SqlCacheDependency("tb", "Contents");
//tb:是在Web.config 文件的 caching 节的 sqlCacheDependency 的databases 元素中定义的数据库的名称。
// Contents: 与 SqlCacheDependency 关联的数据库表的名称。 MgrCache.SetCache(Kits.CacheKey, entity, sqlDep); }
else { ContentsEntity entity = (ContentsEntity)MgrCache.GetCache(Kits.CacheKey); sb = entity.cnt_content; }

 命令aspnet_regsql -C "data source=127.0.0.1;initial catalog= cachedb;user id=sa;password=123" -ed -et -t "Contents"

以下是该工具的命令参数说明:

  -? 显示该工具的帮助功能;

  -S 后接的参数为数据库服务器的名称或者IP地址;

  -U 后接的参数为数据库的登陆用户名;

  -P 后接的参数为数据库的登陆密码;

  -E 使用当前登录用户的 Windows 集成认证进行身份验证。

  -d 后接参数为对哪一个数据库采用SqlCacheDependency功能;

  -C 连接数据库的连接字符串。如果您指定服务器(-S)和登录(-U和-P,或 -E)信息,则此选项不是必需的,因为连接字符串已经包含这些信息。

  -t 后接参数为对哪一个表采用SqlCacheDependency功能;

  -ed 允许对数据库使用SqlCacheDependency功能;

  -dd 禁止对数据库采用SqlCacheDependency功能;

  -et 允许对数据表采用SqlCacheDependency功能;

  -dt 禁止对数据表采用SqlCacheDependency功能;

  -lt 列出当前数据库中有哪些表已经采用sqlcachedependency功能。

            

 

原文地址:https://www.cnblogs.com/soaeon/p/4132205.html