kafka生產者java用戶端

來源:互聯網
上載者:User

標籤:控制   lin   finally   follow   factor   com   mem   data   使用   

producer

  包含一個用於儲存待發送訊息的緩衝池,緩衝池中訊息是還沒來得及傳輸到kafka叢集的訊息。
  位於底層的kafka I/O線程負責將緩衝池中的訊息轉換成請求發送到叢集。如果在結束produce時,沒有調用close()方法,那麼這些資源會發生泄露。
 

常用配置

bootstrap.servers

 用於初始化時建立連結到kafka叢集,以host:port形式,多個以逗號分隔host1:port1,host2:port2; 

 

acks

生產者需要server端在接收到訊息後,進行反饋確認的尺度,主要用於訊息的可靠性傳輸;acks=0表示生產者不需要來自server的確認;
acks=1表示server端將訊息儲存後即可發送ack,而不必等到其他follower角色的都收到了該訊息;acks=all(or acks=-1)意味著server端將等待所有的副本都被接收後才發送確認。

 

retries

生產者發送失敗後,重試的次數 

 


batch.size

當多條訊息發送到同一個partition時,該值控制生產者批量發送訊息的大小,批量發送可以減少生產者到服務端的請求數,有助於提高用戶端和服務端的效能。 

 


linger.ms

預設情況下緩衝區的訊息會被立即發送到服務端,即使緩衝區的空間並沒有被用完。
可以將該值設定為大於0的值,這樣寄件者將等待一段時間後,再向服務端發送請求,以實現每次請求可以儘可能多的發送批量訊息。

 

batch.size

batch.size和linger.ms是兩種實現讓用戶端每次請求儘可能多的發送訊息的機制,它們可以並存使用,並不衝突。 

 


buffer.memory

生產者緩衝區的大小,儲存的是還未來得及發送到server端的訊息,如果生產者的發送速度大於訊息被提交到server端的速度,該緩衝區將被耗盡。 

 

key.serializer,value.serializer

說明了使用何種序列化方式將使用者提供的key和vaule值序列化成位元組。

 

Producer

  

public class Producer {        private static final Logger LOGGER = LoggerFactory.getLogger(Producer.class);      private KafkaProducer<String, String> kafkaProducer;      private Random random = new Random();      private String topic;      private int retry;          public Producer() {        this("my_init");    }        public Producer(String topic) {        this(topic,3);      }        public Producer(String topic,int retry) {         this.topic = topic;           this.retry = retry;          if (null == kafkaProducer) {               Properties props = new Properties();               InputStream inStream = null;               try {                   inStream = this.getClass().getClassLoader().getResourceAsStream("kafka-producer.properties");                   props.load(inStream);                   kafkaProducer = new KafkaProducer<String, String>(props);               } catch (IOException e) {                   LOGGER.error("kafkaProducer初始化失敗:" + e.getMessage(), e);               } finally {                   if (null != inStream) {                       try {                           inStream.close();                       } catch (IOException e) {                           LOGGER.error("kafkaProducer初始化失敗:" + e.getMessage(), e);                       }                   }               }           }      }        /**      * 通過kafkaProducer發送訊息      * @param topic 訊息接收主題      * @param partitionNum  哪一個分區      * @param retry  重試次數      * @param message 具體訊息值      */      public RecordMetadata sendKafkaMessage(final String message) {            ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic, random.nextInt(3), "", message);          Future<RecordMetadata> meta = kafkaProducer.send(record, new Callback() {  
//send方法是非同步,添加訊息到緩衝區等待發送,並立即返回,這使生產者通過批量發送訊息來提高效率 public void onCompletion(RecordMetadata recordMetadata,Exception exception) { if (null != exception) { LOGGER.error("kafka發送訊息失敗:" + exception.getMessage(),exception); retryKakfaMessage(message); } } }); RecordMetadata metadata = null; try { metadata = meta.get(); } catch (InterruptedException e) { } catch (ExecutionException e) {} return metadata; } /** * 當kafka訊息發送失敗後,重試 */ private void retryKakfaMessage(final String retryMessage) { ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic, random.nextInt(3), "", retryMessage); for (int i = 1; i <= retry; i++) { try { kafkaProducer.send(record); return; } catch (Exception e) { LOGGER.error("kafka發送訊息失敗:" + e.getMessage(), e); retryKakfaMessage(retryMessage); } } } /** * kafka執行個體銷毀 */ public void close() { if (null != kafkaProducer) { kafkaProducer.flush(); kafkaProducer.close(); } } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public int getRetry() { return retry; } public void setRetry(int retry) { this.retry = retry; } }

 

TestProducer

  

public class TestProducer {    private static final Logger LOGGER = LoggerFactory.getLogger(TestProducer.class);      public static void main(String[] args) {        ExecutorService executor = Executors.newFixedThreadPool(3);        for(int i=0;i<3;i++){            executor.submit(new Runnable() {                @Override                public void run() {                     String topic = "2017-11-6-test";                     Producer p = new Producer(topic);                     for(int n=1;n<=5;n++){                         String str = "hello world => "+n;                         RecordMetadata message = p.sendKafkaMessage(str);                         LOGGER.info("發送資訊: "+message.topic()+"---"+message.partition()+"---"+message.offset());                     }                     p.close();                }            });        }        System.out.println("this is main");        executor.shutdown();//這個表示 線程執行完之後自動結束        System.out.println("hello world");    }}

 

kafka生產者java用戶端

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.