asp.net基于数据库表的缓存实例

16 篇文章 0 订阅

数据库中某个表中的数据需要频繁访问,此时可以将其保存在cache中,表中数据变化时缓存自动变化。

此功能需.net FrameWork 2.0以上及MS Sql Server 2005以上。

要实现此功能,需要在三个级别上处理:数据库、.net配置文件、页面程序。

一、首先开启数据库缓存依赖功能,并确定数据库是否启用Service Broker。

aspnet_regsql -S <服务器名称> -U <登录账号>-P <登录密码> -d <数据库名称> -ed     

 

执行Select DATABASEpRoPERTYEX('<数据库名称>','IsBrokerEnabled') 或 select is_broker_enabled from sys.databases where name='<数据库名称>'   

结果1 表示Service Broker已经启用,0 表示没有启用

如果没有启用,执行ALTER DATABASE <数据库名称> SET ENABLE_BROKER

 

二、ASP.NET中配置

1、web.config配置:

<system.web>

<caching>
     <sqlCacheDependency enabled="true" pollTime="1000">
       <databases>
         <add name="abico" connectionStringName="testCache"/>
       </databases>
     </sqlCacheDependency>
   </caching>

</system.web>

 

  <connectionStrings>
    <add name="testCache" connectionString="data source=.;initial catalog = test;user id=sa ;password=sa" providerName="System.Data.SqlClient"/>
  </connectionStrings>

2、Global.asax配置:

程序执行时需要设置SqlDependency为启动状态,此时放在Global.asax文件的Application_Start中执行:

    void Application_Start(object sender, EventArgs e)
    {
        //在应用程序启动时运行的代码
        System.Data.SqlClient.SqlDependency.Start(System.Configuration.ConfigurationManager.ConnectionStrings["testCache"].ToString());
    }
   
    void Application_End(object sender, EventArgs e)
    {
        //在应用程序关闭时运行的代码
        System.Data.SqlClient.SqlDependency.Stop(System.Configuration.ConfigurationManager.ConnectionStrings["testCache"].ToString());
    }


 

三、程序页面

    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable myDt = getDataTable();

        GridView1.DataSource = myDt.DefaultView;
        GridView1.DataBind();
    }

    private DataTable getDataTable()
    {
        DataTable dtCache = (DataTable)HttpRuntime.Cache["testCache"];
        if (dtCache != null)
        {
            return dtCache;
        }
        else
        {
            string mySql = "select * from Table1";
            SqlConnection myConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["testCache"].ToString());
            if (myConn.State != ConnectionState.Open)
            {
                myConn.Open();
            }
            SqlCommand myCmd = new SqlCommand(mySql, myConn);
            System.Web.Caching.SqlCacheDependency mySqlDep = new System.Web.Caching.SqlCacheDependency(myCmd);
            SqlDataAdapter mySqlAdapter = new SqlDataAdapter(myCmd);
            DataTable myDt = new DataTable();
            mySqlAdapter.Fill(myDt);
            if (myDt != null)
            {
                HttpRuntime.Cache.Insert("testCache", myDt, mySqlDep);
            }
            return myDt;
        }

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值