1
+ package kafka .examples ;
2
+
3
+ import org .apache .kafka .clients .producer .Callback ;
4
+ import org .apache .kafka .clients .producer .KafkaProducer ;
5
+ import org .apache .kafka .clients .producer .ProducerConfig ;
6
+ import org .apache .kafka .clients .producer .ProducerRecord ;
7
+ import org .apache .kafka .clients .producer .RecordMetadata ;
8
+ import org .apache .kafka .common .serialization .StringSerializer ;
9
+ import org .slf4j .Logger ;
10
+ import org .slf4j .LoggerFactory ;
11
+
12
+ import java .util .Properties ;
13
+
14
+ public class ProducerDemo {
15
+ private static final Logger LOG = LoggerFactory .getLogger (ProducerDemo .class );
16
+ private static final String TOPIC_NAME = "orders" ;
17
+
18
+ public static void main (String [] args ) {
19
+ Properties kafkaProps = new Properties ();
20
+ kafkaProps .put (ProducerConfig .BOOTSTRAP_SERVERS_CONFIG , "localhost:9092" );
21
+ kafkaProps .put (ProducerConfig .KEY_SERIALIZER_CLASS_CONFIG , StringSerializer .class );
22
+ kafkaProps .put (ProducerConfig .VALUE_SERIALIZER_CLASS_CONFIG , StringSerializer .class );
23
+ KafkaProducer <String , String > producer = new KafkaProducer <>(kafkaProps );
24
+
25
+ fireAndForgetMessage (producer , "Fire and forget message..." );
26
+ synchronousSend (producer , "Synchronous message..." );
27
+ asynchronousSend (producer , "Asynchronous message...." );
28
+ }
29
+
30
+ public static void fireAndForgetMessage (KafkaProducer <String , String > producer , String message ) {
31
+ LOG .info ("Fire and forget: {}" , message );
32
+ ProducerRecord <String , String > record = new ProducerRecord <>(TOPIC_NAME , message );
33
+ producer .send (record );
34
+ producer .flush ();
35
+ }
36
+
37
+ public static void synchronousSend (KafkaProducer <String , String > producer , String message ) {
38
+ LOG .info ("synchronous send: {}" , message );
39
+ ProducerRecord <String , String > record = new ProducerRecord <>(TOPIC_NAME , message );
40
+ try {
41
+ LOG .info (producer .send (record ).get ().toString ());
42
+ } catch (Exception e ) {
43
+ e .printStackTrace ();
44
+ }
45
+ }
46
+
47
+ public static void asynchronousSend (KafkaProducer <String , String > producer , String message ) {
48
+ LOG .info ("asynchronous send: {}" , message );
49
+ ProducerRecord <String , String > record = new ProducerRecord <>(TOPIC_NAME , message );
50
+ producer .send (record , new OrdersProducerCallback ());
51
+ producer .flush ();
52
+ }
53
+
54
+ private static class OrdersProducerCallback implements Callback {
55
+
56
+ @ Override
57
+ public void onCompletion (RecordMetadata recordMetadata , Exception e ) {
58
+ if (e != null ) {
59
+ LOG .error (e .toString ());
60
+ } // else the message has been sent successfully
61
+ }
62
+ }
63
+ }
0 commit comments