解决 Kafka 报错 RecordTooLargeException 消息体超限配置修复
排查 Kafka 生产者发送超大消息抛出 org.apache.kafka.common.errors.RecordTooLargeException,调优 max.request.size 与 message.max.bytes。
问题现象
生产者向 Kafka 发送包含大文件、大 JSON 报文或图像数据时,发送 Future 抛出异常:
org.apache.kafka.common.errors.RecordTooLargeException:
The message is 20971520 bytes when serialized which is larger than
the maximum request size you have configured with the max.request.size configuration.
触发根因
Kafka 默认将单条消息的最大体积限制为保守的 1MB(1,048,576 字节)。当序列化后的字节流超过该限制时:
- 生产者拦截:受限于客户端自身的
max.request.size; - Broker 拦截:受限于服务端的
message.max.bytes; - 消费者拦截:受限于下游的
fetch.max.bytes。
解决步骤
1. 调整生产者配置参数(例如放宽至 20MB)
在生产者初始化属性中配置:
max.request.size=20971520
buffer.memory=67108864
2. 在 Broker 端调大主题级与全局级消息大小限制
在 server.properties 中:
message.max.bytes=20971520
replica.fetch.max.bytes=20971520
对已存在的特定主题动态修改配置:
bin/kafka-configs.sh --bootstrap-server localhost:9092 \
--entity-type topics --entity-name heavy_data_topic \
--alter --add-config max.message.bytes=20971520
3. 同步调大消费者抓取限制
fetch.max.bytes=20971520
max.partition.fetch.bytes=20971520
验证确认
再次运行大报文投递测试:
消息顺利投递成功并在下游被完整消费,无任何阻断异常。


