日期:2013-09-17  浏览次数:21006 次

原理:

当数据库中的数据更新时,使用触发器调用外部程序修改Cache依赖的文件,从而使Cache失效。当页面再次请求Cache时,由于请求的Cache已经失效,所以程序将从数据库取数据,并更新Cache。



Sql Server 2000中的触发触发器是一种特殊的存储过程,被定义为在对表或者视图执行INSERT、UPDATE、DELETE操作时执行。



Cache的Insert方法的一个重载版本

Public void Insert(string ,object , CacheDependency)

向Cache中插入具有文件依赖项或键依赖项的对象。[Visual Basic]当任何依赖项更改时,该对象即无效,并从缓存中移除。



代码:



Sql Server触发器:

CREATE TRIGGER BookList_Cache ON [dbo].[BookList]

FOR INSERT, UPDATE, DELETE

AS

Begin

DECLARE @CMDS [nvarchar](100)

--外部程序的路径。BookList -– Cache依赖的文件名称,以参数的形式传递给外部程序。

SET @CMDS = 'C:\Inetpub\wwwroot\TryXML\SqlDepend.exe ' + ' BookList'

Exec Master..xp_cmdshell @CMDS

End



SqlDepend代码:

SqlDepend是一个控制台应用程序。



using System;

using System.IO;

using System.Xml;



namespace SqlDepend

{

///

/// Class1 的摘要说明。

///

class Class1

{

///

/// 应用程序的主入口点。

///

[STAThread]

static void Main(string[] args)

{

//

// TODO: 在此处添加代码以启动应用程序

//

//Cache依赖文件的具体路径

string Path=@"C:\Inetpub\wwwroot\TryXML\Cache\";

//Cache依赖文件的名称。

string _table = args[0].ToString();

Path = Path + _table + ".xml";

if(!File.Exists(Path))

{

File.Create(Path);

}

//产生一随机数,写入依赖文件。

Random _r = new Random( unchecked ( ( int ) DateTime.Now.Ticks ) );

string _value = _r.Next().ToString();

StreamWriter _SWriter = new StreamWriter( File.Open( Path, FileMode.Open, FileAccess.Write ) );

_SWriter.Write( _value );

_SWriter.Close();

}

}

}



web文件:

if(Cache["InvalidataCache"] != null)

{

Response.Write("Cache is not Invalided!");

}

else

{

Response.Write("Cache had Invalided!");

Cache.Insert("InvalidataCache","Hello World!",

new CacheDependency(Server.MapPath(@"Cache\Booklist.xml")));

}