kafka:創建生產者(有/無回調函數示例)


import org.apache.kafka.clients.producer.KafkaProducer;
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM