kafka達到最佳吞吐量的消息大小是10k,然而有些場景需要kafka發送很大的消息,比如消息中含有base64格式的圖片或短視頻信息等。
項目中採用的spring集成kafka模塊,如需支持大消息發送,需要進行以下兩個方面的配置:
1.Kafka服務配置
1.1 broker配置
server.properties中添加:
- message.max.bytes :20000000(20M),這是單個消息的最大值,kafka默認好像是1M左右
- **replica.fetch.max.bytes **:21000000(21M),這是單個消息的最大值broker可複製的消息的最大字節數,比message.max.bytes大,否則broker會接收此消息,但無法將此消息複製出去,從而造成數據丟失,但是不能太大!!!不然複製的時候容易內存溢出
1.2 producer配置
producer.properties中添加:
- max.request.size: 20000000(20M), 這是生產者能請求的最大消息,大於或等於message.max.bytes
1.3 consumer配置
consumer.properties中添加:
- fetch.message.max.bytes: 21000000(21M), 這是消費者能讀取的最大消息,大於或等於message.max.bytes
2.Spring配置
yml或者propertise中配置max.request.size,但實測不生效,需要java中寫config,具體的配置可在https://kafka.apache.org/documentation/#producerconfigs中查找,如下進行java的kafka配置:
@Bean
public Map<String, Object> producerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"10.10.100.100:9092");
props.put(ProducerConfig.RETRIES_CONFIG, 3);
//每次批量發送消息的數量(吞吐量和延時性能),默認16k,batch 越小,producer的吞吐量越低,
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432); //默認32M
props.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, 50000000);
//# 指定消息key和消息體的編解碼方式
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return props;
}