简体   繁体   中英

SQL Server Service Broker Deadlock

I'm investigating a process that I did not build. It uses the service broker to create a queue of contacts that then need an action against them.

There is then a handler that receives 10k records and passes them to a stored procedure to process.

What happens if that final process fails for a deadlock with no error handling? Do these go back into the queue? If not what would I need to do to get them to go back into the queue?

Service broker queues can be accessed from within a transaction. So if you do something like this in your code (the below is pseudo-code; actual robust service broker code is a little beyond the scope of your question):

begin tran
   receive top(10000) message_body
   into @table
   from dbo.yourQueue;

   while(1=1)
   begin
      select top(1) @message = message
      from @table;
      if (@message is null)
         break;
      exec dbo.processMessage @message;
   end
commit tran

… then you're set. What I'm saying is that as long as you're doing your receive and processing in the same transaction, any failure (deadlocks included) will rollback the transaction and put the messages back on the queue. Make sure you read up on poison message handling, though! If you get too many rollbacks, SQL will assume that there's an un-processable message and shut down the queue. That's a bad day when that happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM