1

The NServiceBus documentation lists a benefit of SQL transport as:

Queues support competing consumers (multiple instances of same endpoint feeding off of same queue) so there is no need for distributor in order to scale out the processing

http://docs.particular.net/nservicebus/sqlserver/design

Who does NServiceBus prevent a message from being handled by multiple consumers if multiple consumers have subscribed to the same queue?

Does NServiceBus lock the entire table until the message is handled? Or is the message marked as 'being processed' ??

4

1 回答 1

6

SQL 传输使用非常具体的锁定提示来锁定行并导致其他竞争线程忽略当前锁定的任何行。

NServiceBus.SqlServer 2.2.0(我写这篇文章时的当前版本)开始,使用的 SQL 由我重新格式化,是:

WITH message AS 
(
    SELECT TOP(1) * 
    FROM [{Schema}].[{Queue}] WITH (UPDLOCK, READPAST, ROWLOCK) 
    ORDER BY [RowVersion] ASC
) 
DELETE FROM message 
OUTPUT deleted.Id, deleted.CorrelationId, deleted.ReplyToAddress, 
       deleted.Recoverable, deleted.Expires, deleted.Headers, deleted.Body;

它使用公用表表达式将源数据限制为要返回的一行,然后使用以下锁定提示:

  • UPDLOCK- 锁定数据以进行更新。
  • READPAST- 忽略锁定的行并获取下一个未锁定的行。
  • ROWLOCK- 强制行级锁,不要升级为页锁或表锁。

通过将整个事情执行为删除,然后输出即将删除的数据,我们可以读取数据,如果事务提交,则删除该行。否则,如果事务回滚,则释放锁并等待下一个竞争消费者获取该行。

于 2015-11-04T16:02:46.197 回答