zoukankan      html  css  js  c++  java
  • ASP.NET中的缓存机制

    ASP.NET 提供一个功能完整的缓存引擎,页面可使用该引擎通过 HTTP 请求存储和检索任意对象.
    缓存的生存期与应用程序的生存期相同,也就是说,当应用程序重新启动时,将重新创建缓存。


    将数据添加到缓存中
    1。通过指定其键和值将项添加到缓存中
    Cache["txt"] = "a";
    2.通过使用 Insert(重载Insert方法)方法将项添加到缓存中
    Cache.Insert("txt", "a");
    下列代码显示如何设置相对过期策略。它插入一个项,该项自上次访问后 10 分钟过期。注意 DateTime.MaxValue 的使用,它表示此项没有绝对过期策略。
    DateTime absoluteExpiration=DateTime.MaxValue;
    TimeSpan slidingExpiration=TimeSpan.FromMinutes(10);
    Cache.Insert("txt", "a",null,
    absoluteExpiration,slidingExpiration,
    System.Web.Caching.CacheItemPriority.High,null);
    3.使用 Add 方法将项添加到缓存中
    Add 方法与 Insert 方法具有相同的签名,但它返回表示您所添加项的对象
    DateTime absoluteExpiration=DateTime.MaxValue;
    TimeSpan slidingExpiration=TimeSpan.FromMinutes(10);
    Object Ojb=(string)Cache.Add("txt","a",null,
    absoluteExpiration ,slidingExpiration ,
    System.Web.Caching.CacheItemPriority.High,null);
    string str=(string)Ojb ;
    Response.Write(str);
    结果显示是"a"
    Add 方法使用上没有Insert 方法灵活,使用Add 方法时必须提供7个参数,Insert 方法重载4次,我们可以根据需要选择适当重载方法


    从缓存中取得数据
    方式1:
    string str=(string)Cache.Get("txt");
    Response.Write(str);
    方式2:
    string str1=(string)Cache["txt1"];
    Response.Write(str1);

    查看Cache中所有数据
    System.Text.StringBuilder sb=new System.Text.StringBuilder("",100);
    foreach(DictionaryEntry Caches in Cache)
    {
    sb.Append("key=").Append(Caches.Key.ToString()).Append("
    ") ;
    sb.Append("value=").Append(Caches.Value.ToString()).Append("
    ");
    }
    Response.Write(sb.ToString());
    查看Cache中的项数

    int Count=Cache.Count;
    Response.Write(Count.ToString());


    将数据从缓存中删除

    Cache.Remove("txt");

    使Cache具有文件依赖项或键依赖项的对象
    我们在一页面建立1个按钮,查看CACHE是否存在
    在窗体启动时我们创建CACHE,名称="txt2",数值=数据集ds
    该CACHE与myfile.xml相关联,当myfile.xml文件变化时,txt2CACHE就被自动删除
    private void Page_Load(object sender, System.EventArgs e)
    {
    if( !IsPostBack )
    {
    string FilePath=MapPath("myfile.xml");
    SqlConnection con=new SqlConnection("Uid=sa;database=pubs;");
    SqlDataAdapter da =new SqlDataAdapter("select * from authors",con);
    DataSet ds=new DataSet();
    da.Fill(ds);
    System.Web.Caching.CacheDependency CacheDependencyXmlFile=new System.Web.Caching.CacheDependency(FilePath);
    Cache.Insert("txt2",ds ,CacheDependencyXmlFile);
    }
    }

    为了监视pubs数据库authors表的变化
    我们可以在pubs数据库authors表建立触发器
    一旦authors表中发生增加,删除,修改数据时,触发器会自动修改文件myfile.xml
    一旦myfile.xml文件变化,txt2CACHE就被系统自动删除
    CREATE TRIGGER tr_authors
    ON authors
    FOR INSERT, UPDATE ,delete
    AS
    declare @cmd nvarchar(4000)
    select @cmd='bcp "select convert(nvarchar(30),Getdate(),13)" queryout D:cacheWebCachemyfile.xml -c -Sglc2403 -Usa -P'
    exec master..xp_cmdshell @cmd
    GO

    private void QueryButton_Click(object sender, System.EventArgs e)
    {
    if ( Cache["txt2"]!=null)
    {
    Response.Write("exists");
    }
    else
    {
    Response.Write("not exists");
    }
    }
    首先我们点按钮,显示Cache["txt2"]存在
    现在我们去表authors中任意修改一数据,再点按钮,显示Cache["txt2"]不存在拉

    以上我们是把CACHE是和一个文件相关联,我们还可以把CACHE和文件组关联,建立依赖
    以下我们把CACHE和2个文件(myfile.xml,myfile1.xml)关联,一旦文件组中其中任意一文件变化,Cache会把"txt2"项的数据从CACHE中删除
    string[] FilePath=new String[]{MapPath("myfile.xml"),MapPath("myfile1.xml")};
    System.Web.Caching.CacheDependency CacheDependencyXmlFile=new System.Web.Caching.CacheDependency(FilePath);
    string CacheVaule="a";
    Cache.Insert("txt2", CacheVaule ,CacheDependencyXmlFile);

    缓存依赖可以是文件,还可以是其他对象的键
    下面的代码说明缓存Cache["txt2"]既依赖文件myfile.xml,又依赖缓存中的Cache["txt"],只要这2者任意一样改变,缓存Cache["txt2"]就会清除
    Cache["txt"] = "b";
    string[] FilePath=new String[]{ MapPath("myfile.xml")};
    string[] dependencyKey=new String[]{"txt"};
    SqlConnection con=new SqlConnection("Uid=sa;database=pubs;");
    SqlDataAdapter da =new SqlDataAdapter("select * from authors",con);
    DataSet ds=new DataSet();
    da.Fill(ds);
    System.Web.Caching.CacheDependency CacheDependencyXmlFile=
    new System.Web.Caching.CacheDependency(FilePath,dependencyKey);
    Cache.Insert("txt2",ds ,CacheDependencyXmlFile);

    缓存绝对过期
    缓存Cache["txt3"] 在1小时后自动过期
    DateTime absoluteExpiration =DateTime.Now.AddHours(1);
    Cache.Insert("txt3","aa",null,absoluteExpiration,System.Web.Caching.Cache.NoSlidingExpiration);

    缓存相对(滑动)过期
    注意:如果创建的弹性到期时间小于零或大于一年,则将引发异常
    缓存Cache["txt4"] 在最后一次被访问后1小时自动过期
    TimeSpan slidingExpiration=TimeSpan.FromHours(1);
    Cache.Insert("txt4","4",null,System.Web.Caching.Cache.NoAbsoluteExpiration,slidingExpiration);


    缓存项的优先等级
    当承载 ASP.NET 应用程序的 Web 服务器缺少内存时,Cache 将有选择地清除项来释放系统内存。当向缓存添加项时,可以为其分配与缓存中存储的其他项相比较的相对优先级。在服务器处理大量请求时,分配了较高优先级值的项被从缓存删除的可能性较小,而分配了较低优先级值的项则更有可能被删除。
    由CacheItemPriority 枚举表示,默认为 Normal。
    缓存Cache["txt5"]优先等级设为最高等级,在服务器释放系统内存时,该缓存项最不可能被删除。
    Cache.Insert("txt5","5",null,
    System.Web.Caching.Cache.NoAbsoluteExpiration,
    System.Web.Caching.Cache.NoSlidingExpiration,
    System.Web.Caching.CacheItemPriority.High,null);

    缓存项时通知应用程序的回调方法
    ASP.NET 提供 CacheItemRemovedCallback 委托。它定义编写事件处理程序时使用的签名,当从缓存中删除项时,该事件处理程序将进行响应。

    static System.Web.Caching.CacheItemRemovedReason reason;
    System.Web.Caching.CacheItemRemovedCallback onRemove = null;
    public void RemovedCallback(String k, Object v, System.Web.Caching.CacheItemRemovedReason r)
    {
    itemRemoved = true;
    reason = r;
    }
    onRemove = new System.Web.Caching.CacheItemRemovedCallback (this.RemovedCallback);
    Cache.Insert("txt",ds,null,
    System.Web.Caching.Cache.NoAbsoluteExpiration,
    System.Web.Caching.Cache.NoSlidingExpiration,
    System.Web.Caching.CacheItemPriority.Default,onRemove);

    由于任何原因从Cache中移除时,将调用 RemovedCallback 方法。

    欢迎大家多多交流

  • 相关阅读:
    QT全局热键(用nativeKeycode封装API,不跨平台)
    Android 短信模块分析(二) MMS中四大组件核心功能详解
    一个高效过滤非UTF8字符的C函数(也可用来判断是否utf8)
    Windows-1252对Latin1编码有改变(并不完全兼容),而且Latin1缺失了好多西欧字符(法语,德语,西班牙语都有)
    C++静态库与动态库
    CFBundleName系列参数的含义
    QT完美转换特殊字符的大小写
    Java-继承的应用
    RTTI、虚函数和虚基类的实现方式、开销分析及使用指导(虚函数的开销很小,就2次操作而已)
    delphi如何获得当前操作系统语言环境
  • 原文地址:https://www.cnblogs.com/lip0121/p/3298412.html
Copyright © 2011-2022 走看看