MassTransit

 

Batch Messaging

Page history last edited by drusellers 1 yr ago

Introduction

 

To send a batch of messages to a single consumer, MassTransit has internal support for batch message handling. A generic Batch<T> message is defined that relates the individual messages in a batch and dispatches them to a single consumer.

 

Details

 

Below is an example of a consumer that handles a batch of messages.

 

public class BatchConsumer :
     Consumes<Batch<IndividualBatchMessage>>.Selected
{
     public void Consume(Batch<IndividualBatchMessage> batch)
     {
          // do anything that would happen at the start of a batch

          int messageCount = 0;
          foreach(IndividualBatchMessage message in batch)
          {
               // do the work for each message in the batch
               messageCount++;
          }

          // do anything that would happen after the batch is complete
     }

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

The message must also contain a couple of properties (defined in the BatchedBy<T> interface) so that it can be properly dispatched by the service bus as shown below:

 

public class IndividualBatchMessage :
     BatchedBy<Guid>
{
     public Guid BatchId { get; set; }
     public int BatchLength { get; set; }
}
 

Once the consumer has been registered with the service bus, an application publishing a batch of messages only needs to publish one or more IndividualBatchMessage messages with the same BatchId and BatchLength. The Batch<T> class is only used to combine the message into a single message reception. For example:

 

Guid batchId = Guid.NewGuid();
int batchLength = 10;
for(int index = 0; index < batchLength; index++)

     _bus.Publish(new IndividualBatchMessage(batchId, batchLength));

 

The result would be ten messages published to the endpoints subscribed to the batch. The consumer at each endpoint would receive a single Batch<IndividualBatchMessage> that contains all of the messages that were published to the BatchId. 

Comments (0)

You don't have permission to comment on this page.