My favorites | Sign in
Project Logo
                
Search
for
Updated Jun 16, 2008 by dru.sellers
BatchMessaging  
Batch Messaging

Introduction

Our story for batch messaging is pretty compelling. Through the built-in support for batched reception of messages, MassTransit makes it easy to subscribe to a batch of messages and handle them within a single component invocation.

Details

Let's look at an example component that handles a batch of messages.

// please note that its Consume<Batch<TMessage, TBatchId>>.Selected **
public class BatchServiceComponent : Consumes<Batch<BasicMessage, Guid>>.Selected
{
	public void Consume(Batch<BasicMessage, Guid> message)
	{
		int messageCount = 0;
		foreach (BasicMessage basicMessage in message)
		{
			messageCount++;
		}
	}

	public bool Accept(Batch<BasicMessage, Guid> message)
	{
		return true;
	}
}

This component is able to handle a batch of BasicMessage messages as a single consumption. This makes it possible to perform actions at the start of a batch, an action for each message in the batch, and actions after the batch has been completely received.

Message support is also easy to code. The BasicMessage class is shown below.

[Serializable]
public class BasicMessage : BatchedBy<Guid>
{
	private readonly Guid _batchId;
	private readonly int _batchLength;

	public BasicMessage(Guid batchId, int batchLength)
	{
		_batchId = batchId;
		_batchLength = batchLength;
	}

	public Guid BatchId
	{
		get { return _batchId; }
	}

	public int BatchLength
	{
		get { return _batchLength; }
	}
}

As with other types of correlated messages, the batching uses a simple interface to return the BatchId and the BatchLength.

To register a component to handle batch messages, use the following code:

	_container.AddComponent<BatchServiceComponent>();

	_bus.AddComponent<BatchServiceComponent>();

By registering the component, a new instance will automatically be created for each batch (using IObjectBuilder). One could also subscribe an instance of the class, but that tends to lead towards state management, which is no damn good for nobody.

Publishing Messages

When using the built-in batch handling, the publisher only needs to publish the messages themselves. No specific batch handling is required on the publishing end of the conversation. For example:

private void SendBatch(int batchLength)
{
	Guid batchId = Guid.NewGuid();
		for (int i = 0; i < batchLength; i++)
	{
		_bus.Publish(new BasicMessage(batchId, batchLength));
	}
}

This is a simple example, but shows that the only thing being published is the actual message type (BasicMessage) and not the BatchMessage<> generic.


Sign in to add a comment
Hosted by Google Code