Broker 丢失消息是由于 Kafka 本身的原因造成的,kafka 为了得到更高的性能和吞吐量,将数据异步批量的存储在磁盘中。消息的刷盘过程,为了提高性能,减少刷盘次数,kafka 采用了批量刷盘的做法。
即按照一定的消息量,和时间间隔进行刷盘。这种机制也是由于 linux 操作系统决定的。将数据存储到 linux 操作系统中,会先存储到页缓存(Page cache)中,按照时间或者其他条件进行刷盘(从page cache到file),或者通过 fsync 命令强制刷盘。数据在 page cache 中时,如果系统挂掉,数据会丢失。
Broker在linux服务器上高速读写以及同步到Replica
上图简述了 broker 写数据以及同步的一个过程。broker 写数据只写到 PageCache 中,而 pageCache 位于内存。这部分数据在断电后是会丢失的。pageCache 的数据通过 linux 的 flusher 程序进行刷盘。
刷盘触发条件有三:
Broker 配置刷盘机制,是通过调用 fsync 函数接管了刷盘动作。从单个 Broker 来看,pageCache 的数据会丢失。
Kafka 没有提供同步刷盘的方式。同步刷盘在 RocketMQ 中有实现,实现原理是将异步刷盘的流程进行阻塞,等待响应,类似 ajax 的 callback 或者是 java 的 future。下面是一段 rocketmq 的源码。
GroupCommitRequest request = new GroupCommitRequest(result.getWroteOffset() + result.getWroteBytes());service.putRequest(request);
boolean flushOK = request.waitForFlush(this.defaultMessageStore.getMessageStoreConfig().getSyncFlushTimeout()); // 刷盘
也就是说,理论上,要完全让 Kafka 保证单个 broker 不丢失消息是做不到的,只能通过调整刷盘机制的参数缓解该情况。比如,减少刷盘间隔,减少刷盘数据量大小。时间越短,性能越差,可靠性越好(尽可能可靠)。这是一个选择题。
为了解决该问题,kafka 通过 producer 和 broker 协同处理单个 broker 丢失参数的情况。
一旦 producer 发现 broker 消息丢失,即可自动进行 retry。除非 retry 次数超过阀值(可配置),消息才会丢失。此时需要生产者客户端手动处理该情况。那么 producer 是如何检测到数据丢失的呢?是通过 ack 机制,类似于 http 的三次握手的方式。
The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are allowed: acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won’t generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. acks=allThis means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. This is equivalent to the acks=-1 setting.
以上的引用是 kafka 官方对于参数 acks 的解释(在老版本中,该参数是request.required.acks)。
上面第三点提到了 ISR 的列表的 follower,需要配合另一个参数才能更好的保证 ack 的有效性。ISR 是 Broker 维护的一个“可靠的 follower 列表”,in-sync Replica 列表,broker 的配置包含一个参数:min.insync.replicas。该参数表示ISR 中最少的副本数。如果不设置该值,ISR 中的 follower 列表可能为空。此时相当于 acks=1。
如上图中:
性能依次递减,可靠性依次升高。
producer采取批量发送的示意图
Consumer 消费消息有下面几个步骤:
Consumer 的消费方式主要分为两种:
Consumer 自动提交的机制是根据一定的时间间隔,将收到的消息进行 commit。commit 过程和消费消息的过程是异步的。也就是说,可能存在消费过程未成功(比如抛出异常),commit 消息已经提交了。此时消息就丢失了。
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test");
// 自动提交开关
props.put("enable.auto.commit", "true");
// 自动提交的时间间隔,此处是1s
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("foo", "bar"));
while (true) {
// 调用poll后,1000ms后,消息状态会被改为 committed
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records)
insertIntoDB(record); // 将消息入库,时间可能会超过1000ms
上面的示例是自动提交的例子。如果此时,insertIntoDB(record) 发生异常,消息将会出现丢失。接下来是手动提交的例子:
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test");
// 关闭自动提交,改为手动提交
props.put("enable.auto.commit", "false");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("foo", "bar"));
final int minBatchSize = 200;
List<ConsumerRecord<String, String>> buffer = new ArrayList<>();
while (true) {
// 调用poll后,不会进行auto commit
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
buffer.add(record);
}
if (buffer.size() >= minBatchSize) {
insertIntoDb(buffer);
// 所有消息消费完毕以后,才进行commit操作
consumer.commitSync();
buffer.clear();
}
将提交类型改为手动以后,可以保证消息“至少被消费一次”(at least once)。但此时可能出现重复消费的情况,重复消费不属于本篇讨论范围。
上面两个例子,是直接使用 Consumer 的 High level API,客户端对于 offset 等控制是透明的。也可以采用 Low level API 的方式,手动控制 offset,也可以保证消息不丢,不过会更加复杂。
try {
while(running) {
ConsumerRecords<String, String> records = consumer.poll(Long.MAX_VALUE);
for (TopicPartition partition : records.partitions()) {
List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
for (ConsumerRecord<String, String> record : partitionRecords) {
System.out.println(record.offset() + ": " + record.value());
}
long lastOffset = partitionRecords.get(partitionRecords.size() - 1).offset();
// 精确控制offset
consumer.commitSync(Collections.singletonMap(partition, new OffsetAndMetadata(lastOffset + 1)));
}
}
} finally {
consumer.close();
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!