简单的SqlCacheDependency

时间:2019-06-27 02:37:13

标签: c# asp.net sql-server sql-server-2012 sqlcachedependency

我阅读的几乎所有教程似乎都错误地设置了 SqlCacheDependency 。我相信他们通常会将过时的轮询方法与查询通知方法混合在一起。

以下是许多示例中的两个:


根据我的测试,如果您正在使用代理(MSSQL 2015+),则无需进行任何.config更改,也不需要进行任何SqlCacheDependencyAdmin调用(无需定义表)等)。

我简化一下就可以了...

SqlDependency.Start(connString)
...
queryString = "SELECT ...";
cacheName = "SqlCache" + queryString.GetHashCode();
...
using (var connection = new SqlConnection(connString))
{
    connection.Open();
    var cmd = new SqlCommand(queryString, connection)
    {
        Notification = null, 
        NotificationAutoEnlist = true
    };

    var dependency = new SqlCacheDependency(cmd);

    SqlDataReader reader = cmd.ExecuteReader();
    try
    {
        while (reader.Read())
        {
            // Set the result you want to cache
            data = ...
        }
    }
    finally
    {
        reader.Close();
    }

    HostingEnvironment.Cache.Insert(cacheName, data, dependency);
}

(不包括检查缓存是否为空的代码,因为这只是设置。我只想显示缓存的设置)

这似乎不需要定义查询中涉及的表并在每个表上进行复杂的触发即可。就是这样。

令我惊讶的是,进行查询的规则具有通知:

对于一个测试,我让它运行一个查询1000次,涉及一个名为“ Settings”的表。然后,我更新表中的值并重复查询。

我监视探查器以查找涉及“设置”一词的所有查询,并且查询仅执行了1次(以设置缓存),然后发生了更新语句,然后又重新执行了一次查询(缓存无效,查询再次运行)

我担心在2-3个小时的时间里用正确的方法做这件事时,我会丢失一些东西,这真的很简单吗?

我真的可以只输入我想要的任何查询,它就可以工作吗?我正在寻找在做危险/非标准或我缺少的小字样的任何指针

2 个答案:

答案 0 :(得分:2)

var依赖=新的SqlCacheDependency(cmd); 当您编写这样的查询时,您会在其中自动定义表名。您的连接已具有数据库名。 这不是明确的方法。

这是捕获异常并知道出了什么问题的明确方法。

// Declare the SqlCacheDependency instance, SqlDep. 
        SqlCacheDependency SqlDep = null; 

        // Check the Cache for the SqlSource key. 
        // If it isn't there, create it with a dependency 
        // on a SQL Server table using the SqlCacheDependency class. 
        if (Cache["SqlSource"] == null) { 

            // Because of possible exceptions thrown when this 
            // code runs, use Try...Catch...Finally syntax. 
            try { 
                // Instantiate SqlDep using the SqlCacheDependency constructor. 
                SqlDep = new SqlCacheDependency("Northwind", "Categories"); 
            } 

            // Handle the DatabaseNotEnabledForNotificationException with 
            // a call to the SqlCacheDependencyAdmin.EnableNotifications method. 
            catch (DatabaseNotEnabledForNotificationException exDBDis) { 
                try { 
                    SqlCacheDependencyAdmin.EnableNotifications("Northwind"); 
                } 

                // If the database does not have permissions set for creating tables, 
                // the UnauthorizedAccessException is thrown. Handle it by redirecting 
                // to an error page. 
                catch (UnauthorizedAccessException exPerm) { 
                    Response.Redirect(".\\ErrorPage.htm"); 
                } 
            } 

            // Handle the TableNotEnabledForNotificationException with 
            // a call to the SqlCacheDependencyAdmin.EnableTableForNotifications method. 
            catch (TableNotEnabledForNotificationException exTabDis) { 
                try { 
                    SqlCacheDependencyAdmin.EnableTableForNotifications("Northwind", "Categories"); 
                } 

                // If a SqlException is thrown, redirect to an error page. 
                catch (SqlException exc) { 
                    Response.Redirect(".\\ErrorPage.htm"); 
                } 
            } 

            // If all the other code is successful, add MySource to the Cache 
            // with a dependency on SqlDep. If the Categories table changes, 
            // MySource will be removed from the Cache. Then generate a message 
            // that the data is newly created and added to the cache. 
            finally { 
                Cache.Insert("SqlSource", Source1, SqlDep); 
                CacheMsg.Text = "The data object was created explicitly."; 

            } 
        } 

        else { 
            CacheMsg.Text = "The data was retrieved from the Cache."; 
        }

答案 1 :(得分:0)

https://docs.microsoft.com/en-us/dotnet/api/system.web.caching.sqlcachedependency?view=netframework-4.8中所述:“在SQL Server 2005查询通知中使用SqlCacheDependency对象不需要任何显式配置。”

因此,CMD中具有显式表名,并且ADO.net为您发出正确的Service Broker配置命令。更新表后,SQL Server将发布一条Service Broker消息,指出该表已更新。 ADO.net验证CMD时,它将检查代理中的显式表以进行更新。

这就是与SQlCacheDependency相关的CMD必须使用显式表的原因。