import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
+import org.springframework.kafka.config.KafkaListenerContainerFactory;
+import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.listener.CommonContainerStoppingErrorHandler;
import java.util.function.Consumer;
};
}
+ @Bean
+ public KafkaListenerContainerFactory<?> batchFactory(ConsumerFactory<String, Long> consumerFactory)
+ {
+ ConcurrentKafkaListenerContainerFactory<String, Long> factory =
+ new ConcurrentKafkaListenerContainerFactory<>();
+
+ factory.setConsumerFactory(consumerFactory);
+ factory.setBatchListener(true);
+
+ return factory;
+ }
+
@Bean
public CommonContainerStoppingErrorHandler errorHandler()
{
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
+import java.util.List;
import java.util.function.Consumer;
Consumer<ConsumerRecord<K, V>> handler;
- @KafkaListener(topics = "${consumer.topic}")
- public void receive(ConsumerRecord<K, V> record)
+ @KafkaListener(topics = "${consumer.topic}", containerFactory = "batchFactory")
+ public void receive(List<ConsumerRecord<K, V>> records)
{
- log.info(
- "{} - {}: {}/{} - {}={}",
- id,
- record.offset(),
- record.topic(),
- record.partition(),
- record.key(),
- record.value()
- );
+ // Do something with the data...
+ log.info("{} - Received {} messages", id, records.size());
+ for (ConsumerRecord<K, V> record : records)
+ {
+ log.info(
+ "{} - {}: {}/{} - {}={}",
+ id,
+ record.offset(),
+ record.topic(),
+ record.partition(),
+ record.key(),
+ record.value()
+ );
- handler.accept(record);
+ handler.accept(record);
+ }
}
}