; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import java.util.Properties; public class producer { public static void main(String[] args) { Properties properties = new Properties(); Properties props = new Properties(); // Kafka服务端的主机名和端口号 props.put("bootstrap.servers", "hadoop01:9092"); // 等待所有副本节点的应答 props.put("acks", "all"); // 消息发送最大尝试次数 props.put("retries", 0); // 一批消息处理大小 props.put("batch.size", 16384); // 请求延时 props.put("linger.ms", 1); // 发送缓存区内存大小 props.put("buffer.memory", 33554432); // key序列化 props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); // value序列化 props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> producer = new KafkaProducer<>(props); for (int i = 0; i < 50; i++) { producer.send(new ProducerRecord<String, String>("first", Integer.toString(i), "hello world-" + i)); //创建生产者有回调函数 /* producer.send(new ProducerRecord<String, String>("first", "hello" + i), new Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (metadata != null) { System.err.println(metadata.partition() + "---" + metadata.offset()); } } }); */ } producer.close(); } }
  1. 打开消费者
 kafka-console-consumer.sh --zookeeper hadoop01:2181 --topic first
  1. 运行api代码,结果如下
Using the ConsoleConsumer with old consumer is deprecated and will be removed 
in a future major release. Consider using the new consumer by passing 
[bootstrap- server] instead of [zookeeper].

hello world-0
hello world-1
hello world-2
hello world-3
hello world-4
hello world-5
hello world-6
hello world-7
hello world-8
hello world-9
hello world-10
hello world-11
hello world-12
hello world-13
hello world-14
hello world-15
hello world-16
hello world-17
hello world-18
hello world-19
hello world-20
hello world-21
hello world-22
hello world-23
hello world-24
hello world-25
hello world-26
hello world-27
hello world-28
hello world-29
hello world-30
hello world-31
hello world-32
hello world-33
hello world-34
hello world-35
hello world-36
hello world-37
hello world-38
hello world-39
hello world-40
hello world-41
hello world-42
hello world-43
hello world-44
hello world-45
hello world-46
hello world-47
hello world-48
hello world-49

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-16
  • 2021-04-27
  • 2022-01-08
  • 2022-02-09
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-25
  • 2022-12-23
  • 2021-12-14
  • 2021-11-03
相关资源
相似解决方案