kafka0.8生产者实例

本文简单介绍下kafka0.8的client的producer的实例。

maven

        
            org.apache.kafka
            kafka_2.10
            0.8.2.2
        

初始化

        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 producer = new KafkaProducer<>(props)

准备消息

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

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

发送

同步发送

producer.send(producerRecord).get();

异步发送(默认)

producer.send(producerRecord);

使用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

  • kafka08-documentation
  • Kafka Clients (At-Most-Once, At-Least-Once, Exactly-Once, and Avro Client)

你可能感兴趣的:(kafka0.8生产者实例)