Bota5ky

Kafka学习笔记(十一):Java Producer

Java Producer

public class ProducerDemo {

    private static final Logger log = LoggerFactory.getLogger(ProducerDemo.class.getSimpleName());

    public static void main(String[] args) {
        log.info("I am a Kafka Producer");

        // create Producer Properties
        Properties properties = new Properties();
        properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        // create the Producer
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        // create a producer record
        ProducerRecord<String, String> producerRecord =
            new ProducerRecord<>("demo_java", "hello world");

        // send the data - asynchronous
        producer.send(producerRecord);

        // flush data - synchronous
        producer.flush();

        // flush and close producer
        producer.close();

    }
}

Java Producer Callbacks

producer.send(producerRecord, new Callback() {
    @Override
    public void onCompletion(RecordMetadata metadata, Exception e) {
        // executes every time a record is successfully sent or an exception is thrown
        if (e == null){
            // the record was successfully sent
            log.info("Received new metadata. \n" +
                    "Topic: " + metadata.topic() + "\n" +
                    "Partition: " + metadata.partition() + "\n" +
                    "Offset: " + metadata.offset() + "\n" +
                    "Timestamp: " + metadata.timestamp());
        } else {
            log.error("Error while producing", e);
        }
    }
});

粘性分区:如果发送速度足够快,几条消息可能作为同一批发送到同一分区

partitioner.class = class org.apache.kafka.clients.producer.internals.DefaultPartitioner

DefaultPartitioner 初始化时默认采用 StickyPartitionCache

posted @ 2023-01-08 20:38  Bota5ky  阅读(73)  评论(0编辑  收藏  举报