我在数据库中有许多需要触发应用程序代码的操作。目前我正在使用数据库轮询,但我听说 SQL Server Service Broker 可以为我提供类似 MSMQ 的功能。
- 我可以从运行在不同机器上的 .NET 应用程序监听 SQL Server Service Broker 队列吗?
- 如果是这样,我应该这样做吗?
- 如果没有,你会推荐什么?
我在数据库中有许多需要触发应用程序代码的操作。目前我正在使用数据库轮询,但我听说 SQL Server Service Broker 可以为我提供类似 MSMQ 的功能。
SSB (SQL Service Broker) 有一个名为Activation的功能,它可以将存储过程附加到队列。当队列中有消息要使用时,SQL Server 将在内部运行此过程。队列附加过程可以是 CLR 过程,使托管代码业务逻辑模块能够运行(C#、VB.Net 等)。
内部激活的存储过程的替代方法是让外部客户端使用WAITFOR(RECEIVE ... )
语句“侦听”队列。此语法对于 SSB 是特殊的,并且会执行非池化块,直到有消息要接收。然后应用程序将接收到的消息作为普通的 T-SQL 结果集(如 SELECT)使用。还有一个用于 Service Broker 的 External Activator示例,它利用事件通知机制来了解何时启动应用程序以使用队列中的消息。
如果您想查看利用 SSB 内部激活的 T-SQL 代码示例,请查看异步过程执行。
要回答您的问题:
我可以从运行在不同机器上的 .NET 应用程序监听 SQL Server Service Broker 队列吗?
是的。
If so, should I do it?
If not, what would you recommend?
You might consider using SqlDependency
. It uses Service Broker behind the scenes, but not explicitly.
You can register a SqlDependency
object with a SELECT
query or a stored procedure. If another command changes the data that was returned from the query, then an event will fire. You can register an event handler, and run whatever code you like at that time. Or, you can use SqlCacheDependency
, which will just remove the associated object from the Cache when the event fires.
You can also use Service Broker directly. However, in that case you will need to send and receive your own messages, as with MSMQ.
In load-balanced environments, SqlDependency
is good for cases where code needs to run on every web server (such as flushing the cache). Service Broker messages are better for code than should only run once -- such as sending an email.
In case it helps, I cover both systems in detail with examples in my book (Ultra-Fast ASP.NET).
A easy to use queue library for SQL Service Broker based on rhino-queues