文章目录
同步和异步本质上来讲,其实是打电话和发短信的区别
同步案例图:
异步案例图:
代码案例
同步发送API ,只需要在异步的基础上,添加get()方法即可
package com.apache.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;
import java.util.concurrent.ExecutionException;
public class CustomProducerSync {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//配置
Properties properties = new Properties();
//连接集群
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092,hadoop103:9092");
//指定对应key value序列化类型
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
//创建kafka生产者
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
//发送数据
for (int i = 0; i <= 5; i++) {
kafkaProducer.send(new ProducerRecord<>("first", "org" + i)).get();
}
//关闭资源
kafkaProducer.close();
}
}