• [转].net中Cache的应用


    为了更快的读取数据,我们一般会把常用到的数据加载到Cache中

    在.NET中,Cache的存在可以依赖多中方式,主要用到HttpContext.Current.Cache类

    在这里,我主要写几种依赖方式

    1:不依赖任何条件

    HttpContext.Current.Cache.Insert(string cacheName,object obj)

    理论上是Cache会永久保存,但是当服务器重新启动,内存紧张的时候也会丢失.

    2:HttpContext.Current.Cache.Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);

    //CacheDependency缓存依赖项,absoluteExpiration绝对过期时间,slidingExpiration最后一次访问的时间隔

    //我们主要讲两种Cache依赖

    2.1:文件依赖,so simple//只要文件改动,Cache移出

    HttpContext.Current.Cache.Insert(cacheName,ojb, new System.Web.Caching.CacheDependency(FilePath));

    2.2:SqlServer数据库依赖//我这里是SQL2005

    首先看数据库通知是否可用,记得一定要开启通知

    Select DATABASEpRoPERTYEX('数据库名','IsBrokerEnabled');如果值为1表示可用

    alter database Game176Admin set ENABLE_BROKER ;//开启
    alter database Game176Admin set DISABLE_BROKER;//关闭

    在Global.asax文件中,我们在应用程序开始和结束时要做一些事情

    void Application_Start(object sender, EventArgs e)
        {
            // 在应用程序启动时运行的代码
            try
            {
                System.Data.SqlClient.SqlDependency.Start(string strCon);//开启
            }
            catch { }
        }

        void Application_End(object sender, EventArgs e)
        {
            //  在应用程序关闭时运行的代码
            try
            {
                System.Data.SqlClient.SqlDependency.Stop(string strCon);
            }
            catch { }
        }

    准备工作已经完成

    我们先写一个方法,添加数据库依赖

            void AddSqlDependency(string strCon, string strSql, OnChangeEventHandler sqlDep_OnChange)
            {
                try
                {
                    using (SqlConnection conn = new SqlConnection(strCon))
                    {
                        SqlCommand comm = new SqlCommand(strSql, conn);
                        SqlDependency sqlDep = new SqlDependency(comm);
                        sqlDep.OnChange += sqlDep_OnChange;
                        if (conn.State == ConnectionState.Closed) conn.Open();
                        comm.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    LogUtility.Add(ex);
                }
            }

    //上面这个方法是告诉数据库,当你指定表数据改变,要移出缓存

    我们现在可以来添加了

              MyObject obj= HttpRuntime.Cache["cacheName"] as MyObject;
                    if (null == obj)
                    {
                        try
                        {
                            obj= GetObj(...);
                        }
                        catch (Exception ex)
                        {
                            LogUtility.Add(ex);
                            obj= null;
                        }
                        if (null != obj)
                        {
                            AddSqlDependency(strCon, "select id from dbo.tableName;select id1 from dbo.tableName1",
                            delegate(object sender, SqlNotificationEventArgs e)
                            {
                                //do something

                                HttpRuntime.Cache.Remove("cacheName");
                            });
                            HttpRuntime.Cache.Insert("cacheName", obj);
                        }
                    }

    上面SQL语句中用到的表,只要这些表中的任何数据有改动,数据库都会通知,这时缓存会移动,select的字段和Cache没有关系,只有表名有关系,所有你要选择最小的字段.很多时候,为了这个字段,在设计表的时候都为多加一个最小的依赖列.

    NOTE:任何Cache都可能丢失,使用前一定要做必要的检查,如:

    MyObject obj=HttpContext.Current.Cache("CacheName") as MyObject;

    if(null==obj)

    {

          obj=.......

          HttpContext.Current.Cache.Insert("CacheName",obj);

    }

  • 相关阅读:
    Zero-Copy&sendfile浅析
    Redis数据清除问题
    Redis官方文档》持久化
    GNU C 、ANSI C、标准C、标准c++区别和联系
    有关jQuery valid 验证多个同name属性的input的问题
    jQuery validator 增加多个模板
    archiver error. Connect internal only, until freed. 之解决办法
    链接ftp,把文件或图片上传到ftp指定的文件夹中
    java 数字金额转换中文金额
    java工具类 --千分位方法
  • 原文地址:https://www.cnblogs.com/fromchaos/p/1710892.html
Copyright © 2020-2023  润新知