Tuesday, November 06, 2012

EasyNetQ Publisher Confirms

EasyNetQ is my easy-to-use .NET API for RabbitMQ.

The default AMQP publish is not transactional and doesn't guarantee that your message will actually reach the broker. AMQP does specify a transactional publish, but with RabbitMQ it is extremely slow, around 200 slower than a non-transactional publish, and we haven't supported it via the EasyNetQ API. For high-performance guaranteed delivery it's recommended that you use 'Publisher Confirms'. Simply speaking, this an extension to AMQP that provides a call-back when your message has been successfully received by the broker.

What does 'successfully received' mean? It depends ...

  • A transient message is confirmed the moment it is enqueued.
  • A persistent message is confirmed as soon as it is persisted to disk, or when it is consumed on every queue.
  • An unroutable transient message is confirmed directly it is published.

For more information on publisher confirms, please read the announcement on the RabbitMQ blog.

To use publisher confirms, you must first create the publish channel with publisher confirms on:

var channel = bus.OpenPublishChannel(x => x.WithPublisherConfirms())

Next you must specify success and failure callbacks when you publish your message:

channel.Publish(message, x => 
x.OnSuccess(() =>
{
// do success processing here
})
.OnFailure(() =>
{
// do failure processing here
}));

Be careful not to dispose the publish channel before your call-backs have had a chance to execute.

Here's an example of a simple test. We're publishing 10,000 messages and then waiting for them all to be acknowledged before disposing the channel. There's a timeout, so if the batch takes longer than 10 seconds we abort with an exception.

const int batchSize = 10000;
var callbackCount = 0;
var stopwatch = new Stopwatch();
stopwatch.Start();

using (var channel = bus.OpenPublishChannel(x => x.WithPublisherConfirms()))
{
for (int i = 0; i < batchSize; i++)
{
var message = new MyMessage {Text = string.Format("Hello Message {0}", i)};
channel.Publish(message, x =>
x.OnSuccess(() => {
callbackCount++;
})
.OnFailure(() =>
{
callbackCount++;
}));
}

// wait until all the publications have been acknowleged.
while (callbackCount < batchSize)
{
if (stopwatch.Elapsed.Seconds > 10)
{
throw new ApplicationException("Aborted batch with timeout");
}
Thread.Sleep(10);
}
}

2 comments:

  1. Dude your new API is different how can you change it to work????

    Please help...

    ReplyDelete
  2. Best to ask these kinds of questions on the mailing list.

    ReplyDelete

Note: only a member of this blog may post a comment.