一 环境:
1.kafka使用的是阿里云的消息队列kafka实例。
2.两台kafka消费服务器。
3.每天大概有50w次kafka发送消费。
--------------------------------------------------------------------------------
1.使用kafka批处理配置 factory.setBatchListener(true);
2.然后kafka的接受方法需要这么写:
@KafkaListener(topics = "你的topic", containerFactory = "kafkaListenerContainerFactory", topicPartitions = {
@TopicPartition(partitions = {"0","1"}, topic = "你的topic") })
public void message(List<ConsumerRecord<String, Object>> records,Acknowledgment ack){
if (!records.isEmpty()) {
for (ConsumerRecord<String, Object> record : records) {
if(null!=record&&record.serializedValueSize()!=-1) {
//业务代码
}
}
}
}
可以看到获取到了一个list,正常for循环业务就可以了。@topicPartitions的意思是取那几个分区的数据
3.这样会一次拿取100条数据(配置文件需要设置max-poll-records: 100
)处理上会快很多。
附上我的配置:
spring:
kafka:
consumer:
group-id: 你的groupId
auto-offset-reset: latest
enable-auto-commit: false
max-poll-records: 100
heartbeat-interval: 60000
session-timeout-ms: 300000
max-poll-interval-ms: 600000
request-timeout-ms: 200500