1、Fire-and-forget
这种方式是不管发送成功与否,客户端都会返回成功。尽管大多数的时候Kafka 在发送失败后,会自己重新自动再一次发送消息,但是也会存在丢失消息的风险
ProducerRecord<String, String> record = new ProducerRecord<String, String>(TOPIC, "Msg-Fire-Forget", "Welcome to my home!!! "); try { producer.send(record); } catch (Exception e) { e.printStackTrace(); }finally { producer.close(); }
2、Synchronous send---同步
这种方式是同步发送的方式,会等待future 对象的返回来判断是否发送成功。
ProducerRecord<String, String> record = new ProducerRecord<String, String>(TOPIC, "Msg-Sync", "Sync Message"); try { RecordMetadata rec = producer.send(record).get(); System.out.println(rec.topic()); } catch (Exception e) { e.printStackTrace(); }finally { producer.close(); }
3、Asynchronous send---异步回调
异步发送基于实现了send() 方法的回调函数
ProducerRecord<String, String> record = new ProducerRecord<String, String>(TOPIC, "Msg-Async", "Sync Message"); try { System.out.println("Staring Sending...."); producer.send(record,new Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { System.out.println("Got FeedBack...."); }}); System.out.println("Stop Sending...."); } catch (Exception e) { e.printStackTrace(); }finally { producer.close(); }
参考:https://blog.csdn.net/chenxu_0209/article/details/84775959