Kafka0.8 Producer Example

  kafka

Order

This article briefly introduces the example of producer of kafka0.8 client.

maven

        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.10</artifactId>
            <version>0.8.2.2</version>
        </dependency>

Initialization

        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,brokerAddr);
        props.put(ProducerConfig.CLIENT_ID_CONFIG, "DemoProducer");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        KafkaProducer<String, String> producer = new KafkaProducer<>(props)

Prepare news

                String dataKey = UUID.randomUUID().toString();
                String dataValue = UUID.randomUUID().toString();

                ProducerRecord<String, String> producerRecord = new ProducerRecord<>(
                        topic,
                        dataKey,
                        dataValue
                );

Send

Synchronous transmission

producer.send(producerRecord).get();

Asynchronous transmission (Default)

producer.send(producerRecord);

Use callback

producer.send(producerRecord, new Callback() {
                    @Override
                    public void onCompletion(RecordMetadata metadata, Exception exception) {
                        if(exception != null){
                            LOGGER.error("send msg to {},error:{}",metadata.topic(),exception);
                        }
                    }
                });

doc