博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net 2.0 + sqlserver2005 数据依赖缓存

Posted on 2010-11-12 22:22  itcfj  阅读(234)  评论(0编辑  收藏  举报

asp.net2.0 + sqlserver2005 数据依赖缓存

Asp.net 2.0 提供了一个新的数据缓存功能,就是利用sql server2005 的异步通知功能来实现缓存

1.首先在sqlserver2005 中创建一个test的数据库.添加一个 employee的数据库表.

 

1CREATE TABLE [dbo].[employee](
2    [id] [int] IDENTITY(1,1) NOT NULL,
3    [name] [varchar](50
4) 
5

 

2使用 vs2005 创建一个新的asp.net项目.

web.config如下

 1<?xml version="1.0"?>
 2<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
 3    <appSettings/>
 4    <connectionStrings>
 5        <add name="mySource" connectionString="Data Source=.\sql2005;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=sasa" providerName="System.Data.SqlClient"></add>
 6    </connectionStrings>
 7    <system.web>
 8        <compilation debug="true"/>
 9        <authentication mode="Windows"/>
10    </system.web>
11</configuration>
12

3.编写global.asax文件,启动监听sql2005通知事件.

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        string connStr=ConfigurationManager.ConnectionStrings["mySource"].ConnectionString;
        SqlDependency.Start(connStr);
    }
    
    void Application_End(object sender, EventArgs e) 
    {
        string connStr = ConfigurationManager.ConnectionStrings["mySource"].ConnectionString;
        SqlDependency.Stop(connStr);
    }
</script>

4.编写数据访问代码.创建一个EmployeeData的类,代码如下

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/**//// <summary>
/// EmployeeData 的摘要说明
/// </summary>
public class EmployeeData
{
    public EmployeeData()
    {
    }

    private HttpContext context;

    public DataSet GetCacheData()
    {
        context = HttpContext.Current;
        DataSet cache =(DataSet) context.Cache["employee"];
        if (cache == null)
        {
            return GetData();
        }
        else
        {
            return cache;
        }
    }


    public DataSet GetData()
    {
        string connStr = ConfigurationManager.ConnectionStrings["mySource"].ConnectionString;
        SqlConnection conn = new SqlConnection(connStr);
        SqlDataAdapter adp = new SqlDataAdapter("select id,name from dbo.employee", conn);
        SqlCacheDependency dep = new SqlCacheDependency(adp.SelectCommand);
        DataSet ds=new DataSet();
        adp.Fill(ds);
        context.Cache.Add("employee", ds, dep, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, new CacheItemRemovedCallback(this.DataDiff));
        return ds;
    }

    public void DataDiff(string key, object value, CacheItemRemovedReason reason)
    {
        Console.WriteLine("key:" + key);
        GetData();
    }

}

这里需要注意的是 select语句的写法, 不能使用select *  的方式,一定要在表名前加架构名称 如我们这里的 dbo.employee.

5.编写测试页面代码.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" >
        </asp:GridView>
    </div>
    </form>
</body>
</html>

6.插入后台代码

using System;
using System.Data;
using System.Configuration;
using System.Web.Caching;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        EmployeeData em=new EmployeeData();
        GridView1.DataSource = em.GetCacheData();
        GridView1.DataBind();
    }

}

使用SQLDependency缓存依赖,以下是一个推SQL缓存依赖的例子,当数据库更新后缓存会自动更新
  string conn = "DataSource=.;Initial Catalog=a;Integrated Security=True";

       

      // Cache.Remove("usertb");

       DataTable dt = new DataTable();

       Response.Write(Cache["usertb"].ToString());

       if (Cache["usertb"] == null)

       {

            using (SqlConnection sqlcon= new SqlConnection(conn))

            {

                //SqlDataAdapter sda= new SqlDataAdapter("select * from usertb", sqlcon);

                //System.Web.Caching.SqlCacheDependencysqlDepend = new System.Web.Caching.SqlCacheDependency(sda.SelectCommand);

                //s

                // System .Web.Caching .SqlCa

                ////sqlDepend .

                //sda.Fill(dt);

              

 

               //Cache.Add("usertb",dt, sqlDepend, System.Web.Caching.Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(1), System.Web.Caching.CacheItemPriority.High, null);

 

                SqlDataAdapter adpter= new SqlDataAdapter("Select * From usertb", conn);

             

                System.Web.Caching.SqlCacheDependency sqlDepend = new System.Web.Caching.SqlCacheDependency(adpter.SelectCommand);

                SqlDependency.Start(conn);

               // dt = newDataTable();

                //注意必须在adpter.Fill()前先建立SqlCacheDependency,否则无效

                adpter.Fill(dt);

                Cache.Add("usertb",dt,sqlDepend, System.Web.Caching.Cache.NoAbsoluteExpiration,TimeSpan.FromMinutes(1), System.Web.Caching.CacheItemPriority.High,null);

            }

 

       }

       else

       {

            dt = (DataTable)Cache["usertb"];

       }

       Response.Write(dt.Rows .Count.ToString ());