• batch.size:批次大小,默认16k
延迟为0时不生效
等待时间到前生产数据累积了16k直接拉走
等待时间到了生产数据没满16k也直接拉走
• linger.ms:等待时间,修改为5-100ms
以延迟代价换取效率
• compression.type:压缩snappy
• RecordAccumulator:缓冲区大小,修改为64m
编写生产者
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
public class CustomProducerParameters {
public static void main(String[] args) {
// 1. 创建 kafka 生产者的配置对象
Properties properties = new Properties();
// 2. 给 kafka 配置对象添加配置信息:bootstrap.servers
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop100:9092");
// key,value序列化(必须): key.serializer,value.serializer
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
// batch.size: 批次大小,默认16k
properties.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
// linger.ms: 等待时间,默认0
properties.put(ProducerConfig.LINGER_MS_CONFIG, 5);
// RecordAccumulator:缓冲区大小,默认 32M 即 33554432 :buffer.memory
properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 67108864);
// compression.type:压缩,默认 none,可配置值 gzip、snappy、lz4 和 zstd
properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");
// 3. 创建 kafka 生产者对象
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
// 4. 调用 send 方法,发送消息
for (int i = 0; i < 5; i++) {
kafkaProducer.send(new ProducerRecord<>("first", "你好啊 " + i));
}
// 5. 关闭资源
kafkaProducer.close();
}
}
开启 Kafka 消费者,并启动生产者