asp.net 13 缓存,Session存储

1.缓存

将数据从数据库/文件取出来放在服务器的内存中,这样后面的用来获取数据,不用查询数据库,直接从内存(缓冲)中获取数据,提高了访问的速度,节省了时间,也减轻了数据库的压力。

缓冲空间换时间的技术。

适合放在缓冲中的数据:经常被查询,但是不是经常改动的数据。

(分布式缓冲......Memcache Redis)

2.Cache对象

Cache高速缓冲,其实就是服务器端的状态保持~

(Session与Cache区别:每个用户都有自己单独的Sesson对象;但是放在Cache中的数据是共享的)

Cache对象基本使用方法:

using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CZBK.ItcastProject.WebApp._2015_6_6
{
    public partial class CacheDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //判断缓存中是否有数据.
            if (Cache["userInfoList"] == null)
            {
                BLL.UserInfoService UserInfoService = new BLL.UserInfoService();
                List<UserInfo> list = UserInfoService.GetList();
                //将数据放到缓存中。
                Cache["userInfoList"] = list;
            }
            else
            {
                List<UserInfo> list = (List<UserInfo>)Cache["userInfoList"];
                Response.Write("数据来自缓存");
            }
        }
} }

Cache Insert方法:

using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CZBK.ItcastProject.WebApp._2015_6_6
{
    public partial class CacheDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //判断缓存中是否有数据.
            if (Cache["userInfoList"] == null)
            {
                BLL.UserInfoService UserInfoService = new BLL.UserInfoService();
                List<UserInfo> list = UserInfoService.GetList();
                //将数据放到缓存中。
                Cache.Insert("userInfoList", list, null, DateTime.Now.AddSeconds(5), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, RemoveCache);
                //string key 
                //object value 
                //CacheDependency dependencies 缓存依赖,检测数据库的数据源,如果数据库发生改变,通知缓存失效
                //DateTime absoluteExpiration 绝对过期时间
                //TimeSpan slidingExpiration 滑动过期时间
                //CacheItemPriority priority 缓存优先级
                //CacheItemRemovedCallback onRemoveCallback 委托,缓存删除的回调函数

                Response.Write("数据来自数据库");
                //Cache.Remove("userInfoList");//移除缓存
            }
            else
            {
                List<UserInfo> list = (List<UserInfo>)Cache["userInfoList"];
                Response.Write("数据来自缓存");
            }
        }
        protected void RemoveCache(string key, object value, CacheItemRemovedReason reason)
        {
            if (reason == CacheItemRemovedReason.Expired)
            {
                //缓存移除的原因写到日志中。
            }
        }
    }
}

3.页面缓冲

Duration:缓冲过期时间

VaryByParam:与该页关联的缓存设置的名称。

注:*https://www.cnblogs.com/woxpp/p/3973182.html (更详细)

<%@ OutputCache Duration="5" VaryByParam="*"%>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PageCacheDemo.aspx.cs" 
    Inherits="CZBK.ItcastProject.WebApp._2015_6_6.PageCacheDemo" %>
<%@ OutputCache Duration="5" VaryByParam="*" %>
<!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  runat="server">
    <div>
  <a href="ShOWDetail.aspx?>用户详细信息</a>

 <a href="ShOWDetail.aspx?>用户详细信息</a>
    </div>
        
    </form>
</body>
</html>

4.缓冲依赖

1)文件缓冲依赖 CacheDependency

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CZBK.ItcastProject.WebApp._2015_6_6
{
    public partial class FileCacheDep : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string filePath = Request.MapPath("File.txt");
            if (Cache["fileContent"] == null)
            {
                //文件缓存依赖.
                CacheDependency cDep = new CacheDependency(filePath);
                string fileContent = File.ReadAllText(filePath);
                Cache.Insert("fileContent", fileContent, cDep);
                Response.Write("数据来自文件");
            }
            else
            {
                Response.Write("数据来自缓存:"+Cache["fileContent"].ToString());
            }
        }
    }
}

2)数据库缓冲依赖 SqlCacheDependency

***https://www.cnblogs.com/wbzhao/archive/2012/05/11/2495459.html

web.config 设置缓冲依赖项配置

<!--缓存依赖项配置-->
    <caching>
      <sqlCacheDependency enabled="true">
        <databases>
          <add name="GSSMS" connectionStringName="connStr" pollTime="15000"/>
        </databases>
      </sqlCacheDependency>
    </caching>
using CZBK.ItcastProject.DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CZBK.ItcastProject.WebApp._2015_6_6
{
    public partial class SqlCacheDep : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Cache["customerList"] == null)
            {
                SqlCacheDependency cDep =    new SqlCacheDependency("GSSMS", "Customer");

                string sql = "select * from Customer";
                DataTable da = SqlHelper.GetDataTable(sql, CommandType.Text);
                Cache.Insert("customerList", da, cDep);
                Response.Write("数据来自数据库");
            }
            else
            {
                Response.Write("数据来自缓存");
            }

        }
    }
}

5.Session问题

1)进程外Session存储

Session存储服务器

a.开启asp.net状态服务开启,进程W3Wp.exe

b.应用程序,配置web.config文件,端口号42424

<sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424"/

c.修改注册表 (设置允许远程访问)

位置:C:\Windows\Microsoft.NET\Framework\v4.0.30319

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters 0改成1

**对象标记为可序列化的~

2)数据库Session存储

a.新建ASPSTATE数据库

b.在位置C:\Windows\Microsoft.NET\Framework\v4.0.30319 下运行aspnet_regsql.exe 新建相关表~

c..在位置C:\Windows\Microsoft.NET\Framework\v4.0.30319 下执行sql脚本文件:永久存储-InstallPersistSqlState.sql; 临时存储-InstallSqlState.sql

d.Webconfig配置文件

<sessionState mode="SQLServer"/>

*Session信息存储在表ASPStateTempSessions中

3)Memcache/Redis 分布式存储

6.错误页面配置

<customErrors mode="On" defaultRedirect="MyErrorPage.html">
      <error statusCode="403" redirect="NoAccess.htm" />
      <error statusCode="404" redirect="FileNotFound.html" />
    </customErrors>

*mode节点,三种情况:on 总是显示定制错误页面;off 直接调用堆栈等异常信息;RemoteOnly 本机的访问显示调用堆栈等异常信息,对于外部用户的显示定制错误页面

*statusCode 响应状态码