序
本文简单介绍下kafka0.8的client的producer的实例。
maven
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.10</artifactId>
<version>0.8.2.2</version>
</dependency>
初始化
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)
准备消息
String dataKey = UUID.randomUUID().toString();
String dataValue = UUID.randomUUID().toString();
ProducerRecord<String, String> 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);
}
}
});
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。