Batch Message Sending

In the case of certain requirements on throughput, Apache RocketMQ can send messages after grouping them into batches. The approach is able to increase throughput and decrease the times of API and network calls.

batch

  1. public class SimpleBatchProducer {
  2. public static void main(String[] args) throws Exception {
  3. DefaultMQProducer producer = new DefaultMQProducer("BatchProducerGroupName");
  4. producer.start();
  5. //If you just send messages of no more than 1MiB at a time, it is easy to use batch
  6. //Messages of the same batch should have: same topic, same waitStoreMsgOK and no schedule support
  7. String topic = "BatchTest";
  8. List<Message> messages = new ArrayList<>();
  9. messages.add(new Message(topic, "Tag", "OrderID001", "Hello world 0".getBytes()));
  10. messages.add(new Message(topic, "Tag", "OrderID002", "Hello world 1".getBytes()));
  11. messages.add(new Message(topic, "Tag", "OrderID003", "Hello world 2".getBytes()));
  12. producer.send(messages);
  13. }
  14. }

Batch Message Sending - 图2note

The call here is simple, where it packages the message as Collection<Message> msgs and passes it into the method as a parameter. There are two things to note here. First of all, the size of the batch message cannot exceed 1 MiB, otherwise, it needs to be split. Secondly, the message topic within the same batch must be identical.