事务中的 Service Broker 消息

Service Broker messages inside a transaction

我正在编写一个将执行以下操作的存储过程:

  1. 开始交易
  2. 执行一些任务
  3. 使用 Service Broker 启动后台进程
  4. 等待来自 Service Broker 的响应消息(带有作业状态)
  5. COMMIT 或 ROLLBACK 事务,取决于响应消息

问题是 Service Broker 通信在 TRANSACTION:

中不工作

这是我的代码的摘录:

-- Comment out the following line to make everything work
begin tran t1

DECLARE @Update_Msg XML([sb].[Service_Broker_xxx_Schemas]) = '
<Request xmlns="xxx">
  <Table xmlns="xxx">
    <Fields>
      xxx
    </Fields>
  </Table>
  <Requested_By>xxx</Requested_By>
</Request>'

DECLARE @conversation_handle UNIQUEIDENTIFIER
            ,@message_body varbinary(max)
            ,@message_type_name nvarchar(256)
            ,@timestamp datetime2

        BEGIN DIALOG CONVERSATION @conversation_handle
        FROM SERVICE [xxx_Initiating_Service]
        TO SERVICE 'xxx_Target_Service'
        ON CONTRACT xxx_Contract
        WITH ENCRYPTION = OFF;

        SEND ON CONVERSATION @conversation_handle
        MESSAGE TYPE [xxx_Command](@Update_Msg);


select * from sys.transmission_queue with(nolock)
--PRINT @conversation_handle

WAITFOR (
    -- just handle one message at a time
    RECEIVE TOP(1)   @conversation_handle = conversation_handle     -- the identifier of the dialog this message was received on
                    ,@message_type_name = message_type_name
                    ,@message_body=message_body                     -- the message contents
                    ,@timestamp = GETDATE()
                    FROM [sb].[xxx_Initiator_Queue]
                    WHERE conversation_handle = @conversation_handle
), TIMEOUT 1000  -- if the queue is empty for one second, give UPDATE and go away
IF @@ROWCOUNT > 0
BEGIN
        SELECT @@ROWCOUNT, @message_type_name, CONVERT(XML, @message_body)
        END CONVERSATION @conversation_handle;
END
ELSE
BEGIN
    PRINT 'Did not receive any response from Service Broker.'
END

-- Comment out the following line to make everything work
commit tran t1

在事务中实现 Service Broker 消息传递的正确方法是什么?

通过 Service Broker 发送消息是事务性的。也就是说,如果您执行 begin tran; send;,直到您 commit.

才真正发送消息