文章目录
1. 需求
现有如下需求,以kafka作为source,使用pushgateway+prometheus架构实时统计flink任务的消费偏移量current-offset和分区偏移量总长度log-end-offset,并计算两者差值得到消费延迟lag,如图:

2. 名词解释
2.1 committed-offsets
每一次kafka消费者调用consumer.poll()后得到一批数据,然后会调用consumer.commitAsync()之类的方法进行提交,代码如下:
ConsumerRecords<byte[], byte[]> records = consumer.poll(pollTimeoutMs);
for (ConsumerRecord<byte[], byte[]> record : records) {
...
}
consumer.commitAsync();
提交后的offset会被存储到zookeeper(已废弃)或者kafka内部topic _consumer_offsets中
2.2 current-offsets
指一次poll()方法所拉取的一批数据的最大的那个偏移量,因此current-offsets是业务强相关的,无法在kafka broker或者kafka client中查询到。在flink kafka source connector中,current-offsets有如下诠释:
This refers to the offset of the last element that we retrieved and emitted successfully
2.3 visible-offset(我自己命名的)
topic中的可见消息总量,当consumer的隔离级别为read_uncommitted,visible-offset等于high watermark;当consumer的隔离级别为read_committed,visible-offset等于last stable offset
what is visible offset
2.4 log-end-offset
待写入的最新消息的偏移
3. 自定义Metrics
那么,为了满足需求,我们究竟需要使用上述的哪些指标呢?我们来分析一下flink kafka source connector源码中关于offset的提交。
3.1 flink kafka source connector源码分析
flink kafka source connector中共有三种提交模式:
public enum OffsetCommitMode {
/** Completely disable offset committing. */
DISABLED,
/** Commit offsets back to Kafka only when checkpoints are completed. */
ON_CHECKPOINTS,
/** Commit offsets periodically back to Kafka, using the auto commit functionality of internal Kafka clients. */
KAFKA_PERIODIC;
}
3.1.2 周期提交
Properties properties = new Properties();
properties.put("enable.auto.commit", "true");
properties.setProperty("auto.commit.interval.ms", "1000");
new FlinkKafkaConsumer<>("foo", new KafkaEventSchema(), properties)
这种提交模式下,我们显然只能使用current-offsets作为监控指标,因为committed-offsets是周期提交的,当到达周期准备提交offset时,flink已经处理了千条万条数据了
3.1.3 Checkpoint时提交
在做 checkpoint 的时候会调用 FlinkKafkaConsumerBase#snapshotState方法,其中 pendingOffsetsToCommit 会保存要提交的 offset。
public final void snapshotState(FunctionSnapshotContext context) throws Exception {
if (offsetCommitMode == OffsetCommitMode.ON_CHECKPOINTS) {
// the map cannot be asynchronously updated, because only one checkpoint call can happen
// on this function at a time: either snapshotState() or notifyCheckpointComplete()
// 保存等待提交的current-offsets
pendingOffsetsToCommit.put(context.getCheckpointId(), currentOffsets);
}
for (Map.Entry<KafkaTopicPartition, Long> kafkaTopicPartitionLongEntry : currentOffsets.entrySet()) {
// 将各个分区的current-offset写入状态
unionOffsetStates.add(
Tuple2.of(kafkaTopicPartitionLongEntry.getKey(), kafkaTopicPartitionLongEntry.getValue()));

本文探讨了Flink从Kafka消费数据时如何监控消费延迟。通过解析flink kafka source connector源码,介绍了committed-offsets、current-offsets、visible-offset和log-end-offset等关键概念。在周期提交和Checkpoint时提交的场景下,分析了适用于监控的offset指标。最后,讲解了如何定义HighWatermark Metrics,以计算并监控消费延迟。
最低0.47元/天 解锁文章
479

被折叠的 条评论
为什么被折叠?



