Bootstrap

Kafka常见问题之 org.apache.kafka.common.errors.RecordTooLargeException

Kafka常见问题之 org.apache.kafka.common.errors.RecordTooLargeException: The message is 1,048,576 bytes when serialized which is larger than the maximum request size.

1. 错误解析

错误信息:

org.apache.kafka.common.errors.RecordTooLargeException: The message is 1,048,576 bytes when serialized which is larger than the maximum request size.

这个错误表明,Kafka 生产者在发送消息时,单条消息的序列化大小超出了 Kafka 允许的最大请求大小(默认 1MB,即 1,048,576 字节)。

2. 错误原因

  1. Kafka 生产者端限制

    • max.request.size(默认 1MB):生产者允许的最大单个请求大小。
  2. Kafka 代理端(Broker)限制

    • message.max.bytes(默认 1MB):Kafka Broker 允许的单条消息最大大小。
  3. Kafka 主题端(Topic)限制

    • max.message.bytes(默认 1MB):Kafka 主题允许的单条消息最大大小。
  4. Kafka 消费端限制

    • fetch.message.max.bytes:消费者可拉取的最大消息大小,若小于生产者消息大小,会导致消费者无法消费。

3. 错误复现案例

3.1 生产者发送超大消息

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

public class LargeMessageProducer {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("max.request.size", 1048576); // 1MB,默认值

        KafkaProducer<String, String> producer = new KafkaProducer<>(props);

        String topic = "test-topic";
        String largeMessage = "A".repeat(1048577); // 1MB + 1 字节的消息

        ProducerRecord<String, String> record = new ProducerRecord<>(topic, largeMessage);

        try {
            producer.send(record);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            producer.close();
        }
    }
}

结果:

org.apache.kafka.common.errors.RecordTooLargeException: The message is 1,048,577 bytes when serialized which is larger than the maximum request size.

4. 解决方案

4.1 方法 1:调整 Kafka 生产者配置**

KafkaProducer 配置中增加 max.request.size,提高消息允许的最大大小:

props.put("max.request.size", 5242880); // 5MB

4.2 方法 2:调整 Kafka Broker 配置

修改 server.properties

message.max.bytes=5242880  # 5MB
replica.fetch.max.bytes=5242880  # 让 Follower 可以拉取大消息

重启 Kafka:

bin/kafka-server-stop.sh
bin/kafka-server-start.sh -daemon config/server.properties

4.3 方法 3:调整 Kafka 主题配置

kafka-configs.sh --alter --zookeeper localhost:2181 --entity-type topics --entity-name test-topic --add-config max.message.bytes=5242880

4.4 方法 4:调整 Kafka 消费者配置

props.put("fetch.message.max.bytes", 5242880);

4.5 方法 5:大消息拆分

  • 将大消息拆分成多个小消息,并在消费端重组。

5. 最佳实践:

  1. 避免发送超大消息,Kafka 设计用于小消息(<1MB)。
  2. 使用压缩
    props.put("compression.type", "gzip"); // 也可以是 lz4, snappy
    
  3. 利用 Kafka 分片,拆分大文件存储到多个分区。
;