kafka入门,提高生产者吞吐量练习(七)

修改配置Java

batch.size 批次大小,默认16k
linger,ms 等待时间,修改为5-100ms
compression.type 压缩snappy
RecordAccmulator 缓冲区大小,修改为64m

代码例子

package com.longer.producer;

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) {
        //创建kafka配置对象
        Properties properties = new Properties();
        // 给 kafka 配置对象添加配置信息
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop100:9092");
        //序列化
        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, 0);
        //RecordAccumulator:缓冲区大小,默认32M:buffer.memory
        properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        //compression.type:压缩,默认none,可配置值gzip、snappy、lz4和zstd
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");
        //创建kafka生产对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);
        //调用 send 方法,发送消息
        for (int i = 0; i < 5; i++) {
            producer.send(new ProducerRecord<>("first", "hi," + i));
        }
        //关闭资源
        producer.close();
    }
}

你可能感兴趣的:(kafka,分布式)