事务中的Service Broker消息

Ser*_*rge 2 sql-server transactions service-broker

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

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

问题是Service Broker通信在以下内容中不起作用TRANSACTION:

  • 消息队列,使激活,但关联的存储过程执行(PRINT在存储过程中的语句不写入错误日志文件中)
  • RECEIVE 命令超时

这是我的代码的摘录:

-- 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
Run Code Online (Sandbox Code Playgroud)

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

Ben*_*hul 6

通过Service Broker发送消息是事务性的.也就是说,如果你这样做begin tran; send;,直到你才真正发送消息commit.