依赖
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>3.0.0</version>
</dependency>
创建toptic主题
# 创建 test topic
bin/kafka-topics.sh --bootstrap-server 192.168.25.129:9092 --create --partitions 1 --replication-factor 3
# 查看当前服务器中的所有 topic
bin/kafka-topics.sh --bootstrap-server 192.168.25.129:9092 --list
同步发送
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 {
// 0 配置
Properties properties = new Properties();
// 连接集群 bootstrap.servers
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.25.129:9092,192.168.25.128:9092");
// 指定对应的key和value的序列化类型 key.serializer
// properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
// 1 创建kafka生产者对象
// KafkaProducer<K, V>
// 泛型K为key一般为String类型 泛型V为传递消息的类型,此处发送字符串用String类型
// 下列发送数据即为 “” “hello ”
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
// 2 发送数据
for (int i = 0; i < 5; i++) {
// 只需在异步发送的基础上,再调用一下 get()方法即可
kafkaProducer.send(new ProducerRecord<>("test","hello "+i)).get();
}
// 3 关闭资源
kafkaProducer.close();
}
}