在Kafka中,消费者可以通过设置enable.auto.commit
属性来控制是否自动提交偏移量。要实现定时提交,你可以使用以下方法:
ScheduledExecutorService
来定时提交偏移量。首先,创建一个ScheduledExecutorService
实例,然后在一个固定的时间间隔内提交偏移量。这里是一个简单的示例:
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TimedKafkaConsumer {
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test-group");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("enable.auto.commit", "false");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("test-topic"));
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(() -> {
consumer.commitSync();
}, 0, 5, TimeUnit.SECONDS);
}
}
在这个示例中,我们创建了一个ScheduledExecutorService
实例,每隔5秒提交一次偏移量。请注意,我们将enable.auto.commit
属性设置为false
,以便手动提交偏移量。
poll()
方法来定时提交偏移量。在这种方法中,你需要在一个循环中调用poll()
方法,并在处理完消息后提交偏移量。这里是一个简单的示例:
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
public class TimedKafkaConsumer {
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test-group");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("enable.auto.commit", "false");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("test-topic"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
// 处理消息
System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
}
consumer.commitSync();
}
}
}
在这个示例中,我们使用一个无限循环来定期调用poll()
方法,并在处理完消息后提交偏移量。请注意,我们将enable.auto.commit
属性设置为false
,以便手动提交偏移量。
这两种方法都可以实现定时提交偏移量的目的,你可以根据自己的需求选择合适的方法。