SqlDependency缓存数据库表小案例

SqlDependency的简介:

  SqlDependency是outputcache网页缓存的一个参数,它的作用是指定缓存失效的数据库依赖项,可以具体到数据库和表。

SqlDependency能解决什么问题?

Asp.Net中的cache可以设置一个过期时间,但设置多久合适呢?长了浪费,短了就失去缓存的意义了。使用SqlDependency进行缓存则可以解决这个问题。

SqlDependency是.net2.0封装的一个类型,要配合sql2005或以上版本才能使用。

另外,SqlDependency类需要数据库的ServiceBroker来支持,当数据库中的数据发生变化时通知应用程序更新缓存,这才是最有效的缓存方式。

应用:

   1启动数据库的ServiceBroker的服务

       (1)查询是否启动ServiceBroker服务Select  DATABASEpRoPERTYEX('数据库名称','IsBrokerEnabled') 1表示启动,0表示尚未启动

     (2)ALTER  DATABASE  <数据库名称>  SET  ENABLE_BROKER;   该sql用于启动ServiceBroker服务  

  2配置webconfig

    (1)添加链接语句的xml

<connectionStrings>
<add name="Shop" providerName="System.Data.SqlClient" connectionString="Data Source=.; Initial Catalog=数据库名称; Persist Security Info=True;User ID=用户名;Password=密码"/>
</connectionStrings>

    (2)在<system.web>节点中添加缓存配置的xml

<caching>
      <sqlCacheDependency enabled="true">
        <databases>
          <add name="CacheDependency_NHibernateSampleDb" connectionStringName="链接字符串的名字" pollTime="1500"/>
        </databases>
      </sqlCacheDependency>
    </caching>

    (3)编写底层代码(功用方法)

 /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="CacheName">缓存的名称</param>
        /// <param name="TableName">缓存的数据表的名称</param>
        /// <param name="sqlStr">sql语句</param>
        /// <returns></returns>
        public static DataSet GetCacheData(string CacheName, string TableName, string sqlStr)
        {
            System.Web.Caching.Cache Cache = HttpRuntime.Cache;
            //要检测的数据库
            System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(
                "通过xml得到的链接字符串");
            //初检测数据库中要检测的表
            System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(
                "通过xml得到的链接字符串", TableName);
            System.Web.Caching.SqlCacheDependency scd = new System.Web.Caching.SqlCacheDependency("CacheDependency_NHibernateSampleDb", TableName);


            //此处可以加入自己的其它方法,如重新从数据库取得资料
            DataSet ds = new DataSet();
            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection("通过xml得到的链接字符串"))
            {
                string sql = sqlStr;

                using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
                {
                    SqlDependency.Start("通过xml得到的链接字符串");
                    System.Web.Caching.SqlCacheDependency dependency = new System.Web.Caching.SqlCacheDependency(command);
                    using (System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter()) //查询数据
                    {
                        adapter.SelectCommand = command;
                        adapter.Fill(ds);
                    }
                    Cache.Insert(CacheName, ds, scd);
                }

            }
            return ds;
        }

    (4)应用

 public void GetMAxPriceByCach(HttpContext context)
    {
        var biddId = context.Request["biddId"];
        decimal CountDownPrice = new BLL.BiddingManager().GetALLvw_BiddingProductByBiddingId(Convert.ToInt32(biddId)).CountDownPrice;//获取起拍价格
        //创建缓存
        System.Web.Caching.Cache Cache = HttpRuntime.Cache;
        //创建数据集
        DataSet ds = new DataSet();
        //拼写sql语句
        string sqlStr = "select Count(*) as num from Auction where BiddingId=" + biddId + ";" + "select Max(Auctiomnoney) as pri from Auction where BiddingId=" + biddId + "";
        //判断缓存是不是为空 如果为空则通过底层方法得到新的数据 否则直接从缓存中读取数据
        if (Cache["data_" + biddId] == null)
        {
            ds = Comm.ExpansionClass.GetCacheData("data_" + biddId, "Auction", sqlStr);
        }
        else
        {
            ds = (DataSet)Cache["data_" + biddId];
        }

        string maxPrice = "0";
        if (ds.Tables[0].Rows[0]["num"].ToString() == "0")
        {
            maxPrice = CountDownPrice.ToString("f2");
        }
        else
        {
            maxPrice = decimal.Parse(ds.Tables[1].Rows[0]["pri"].ToString()).ToString("f2");
        }
        context.Response.Write("{\"maxPrice\":\"" + maxPrice + "\"}");
    }

这样这个用SqlDependency他实现的缓存小案例就技术啦!只有缓存的数据表中的数据发生增删改查等变化的时候才会重新根绝传入的sql重新读取数据库中的数据。值得注意的是:他只能执行简单的sql语句,在sql语句中不能带有用*,不能用top,不能用函数,包括聚合函数,不能用子查询,包括where后的子查询,不能用外连接,自连接,不能用临时表,不能用变量,不能用视图,不能垮库,表名之前必须加类似dbo数据库所有者这样的前缀

 

posted @ 2015-03-16 16:00  流浪的狸猫  阅读(333)  评论(0编辑  收藏  举报