1.必备配置
#开启批量消费
spring.cloud.stream.bindings.<input-in-0>.consumer.batch-mode=true
2.消费者代码
无法像想象那样用Consumer<List<Message>>来接受事件,需要先获取事件数组,顺序跟事件是一样的
@Bean
public Consumer<Message<List<String>>> callEndConsumer() {
return event->{
List<String> payload = event.getPayload();
// 获取header Map<String,byte[]> 顺序和payload一致
List<Map<String, byte[]>> headers = event.getHeaders().get(KafkaHeaders.BATCH_CONVERTED_HEADERS,List.class);
for (int i = 0; i < payload.size(); i++) {
log.info("{},{}", Opt.ofNullable(headers.get(i).get("eventType")).map(e->new String(e)).get(),payload.get(i));
}
};
}