SQL Server 提供了一种事件通知机制,其中分布式缓存就像 NCache 可以通过以下方式注册自己以获取更改通知 SqlCacheDependency 然后在数据库中的基础数据更改时接收来自 SQL Server 的通知。 这允许 NCache 立即使相应的缓存项无效或重新加载,这使缓存始终与数据库同步。 然而, SqlCacheDependency 可以成为将缓存与数据库同步的一种非常耗费资源的方式。
一个更好的选择是编写一个 CLR 存储过程来连接 NCache 从 SQL Server 中直接更新或使相应的缓存项无效。 它的资源效率更高,因为它不创建与 SqlCacheDependency. 而且,它也不会触发 .NET 事件 NCache. 相反,它打开了一个 NCache 客户端连接并直接告诉 NCache 是否使缓存项无效或重新加载。 而且,这种联系与 NCache 高度优化,比 .NET 事件更快更轻。
use Northwind
alter database Northwind
set trustworthy on;
go
drop assembly SMdiagnostics
drop assembly [System.Web]
drop assembly [System.Messaging]
drop assembly [System.ServiceModel]
drop assembly [System.Management]
CREATE ASSEMBLY SMdiagnostics AUTHORIZATION dbo FROM N'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication
Foundation\SMdiagnostics.dll' WITH permission_set = unsafe
CREATE ASSEMBLY [System.Web] AUTHORIZATION dbo FROM N'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Web.dll' WITH permission_set = unsafe
CREATE ASSEMBLY [System.Management] AUTHORIZATION dbo FROM N'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.management.dll' WITH permission_set = unsafe
CREATE ASSEMBLY [System.Messaging] AUTHORIZATION dbo FROM N'C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Messaging.dll' WITH permission_set = unsafe
CREATE ASSEMBLY [System.ServiceModel] AUTHORIZATION dbo FROM N'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\System.ServiceModel.dll' WITH permission_set = unsafe
CREATE ASSEMBLY NCache from N'C:\Program Files\NCache\bin\assembly\2.0\Alachisoft.NCache.Web.dll' WITH permission_set = unsafe
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void TestSProc(string cacheName)
{
//--- Put your code here
SqlPipe sp = SqlContext.Pipe;
try
{
sp.Send("Starting .....");
if (string.IsNullOrEmpty(cacheName))
cacheName = "mycache";
Cache _cache = NCache.InitializeCache(cacheName);
_cache.Insert("key", DateTime.Now.ToString());
sp.Send("Test is completed ...");
}
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO
基于 CLR 的存储过程或触发器可以大大提高应用程序的性能。 SqlCacheDependency 这相对较慢,并且对于大型数据集来说可能是压倒性的。