批量消息发送

在对吞吐率有一定要求的情况下,Apache RocketMQ可以将一些消息聚成一批以后进行发送,可以增加吞吐率,并减少API和网络调用次数。

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. }

批量消息发送 - 图2备注

这里调用非常简单,将消息打包成 Collection<Message> msgs 传入方法中即可,需要注意的是批量消息的大小不能超过 1MiB(否则需要自行分割),其次同一批 batch 中 topic 必须相同。