Initiale Lese-Position auf die älteste bekannte Nachricht gesetzt
[demos/kafka/training] / src / main / java / de / juplo / kafka / SimpleConsumer.java
1 package de.juplo.kafka;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRecord;
5 import org.apache.kafka.clients.consumer.ConsumerRecords;
6 import org.apache.kafka.clients.consumer.KafkaConsumer;
7 import org.apache.kafka.common.errors.WakeupException;
8 import org.apache.kafka.common.serialization.StringDeserializer;
9
10 import java.time.Duration;
11 import java.util.Arrays;
12 import java.util.Properties;
13
14
15 @Slf4j
16 public class SimpleConsumer
17 {
18   private final String id;
19   private final String topic;
20   private final KafkaConsumer<String, String> consumer;
21
22   private volatile boolean running = false;
23   private long consumed = 0;
24
25   public SimpleConsumer(String broker, String topic, String groupId, String clientId)
26   {
27     Properties props = new Properties();
28     props.put("bootstrap.servers", broker);
29     props.put("group.id", groupId); // ID für die Offset-Commits
30     props.put("client.id", clientId); // Nur zur Wiedererkennung
31     props.put("auto.offset.reset", "earliest"); // Von Beginn an lesen
32     props.put("partition.assignment.strategy", "org.apache.kafka.clients.consumer.CooperativeStickyAssignor");
33     props.put("key.deserializer", StringDeserializer.class.getName());
34     props.put("value.deserializer", StringDeserializer.class.getName());
35
36     consumer = new KafkaConsumer<>(props);
37
38     this.topic = topic;
39     this.id = clientId;
40   }
41
42
43   public void run()
44   {
45     try
46     {
47       log.info("{} - Subscribing to topic test", id);
48       consumer.subscribe(Arrays.asList("test"));
49       running = true;
50
51       while (true)
52       {
53         ConsumerRecords<String, String> records =
54             consumer.poll(Duration.ofSeconds(1));
55
56         log.info("{} - Received {} messages", id, records.count());
57         for (ConsumerRecord<String, String> record : records)
58         {
59           consumed++;
60           log.info(
61               "{} - {}: {}/{} - {}={}",
62               id,
63               record.offset(),
64               record.topic(),
65               record.partition(),
66               record.key(),
67               record.value()
68           );
69         }
70       }
71     }
72     catch(WakeupException e)
73     {
74       log.info("{} - Consumer was signaled to finish its work", id);
75     }
76     catch(Exception e)
77     {
78       log.error("{} - Unexpected error: {}", id, e.toString());
79     }
80     finally
81     {
82       running = false;
83       log.info("{} - Closing the KafkaConsumer", id);
84       consumer.close();
85       log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
86     }
87   }
88
89
90   public static void main(String[] args) throws Exception
91   {
92     String broker = ":9092";
93     String topic = "test";
94     String groupId = "my-group";
95     String clientId = "DEV";
96
97     switch (args.length)
98     {
99       case 4:
100         clientId = args[3];
101       case 3:
102         groupId = args[2];
103       case 2:
104         topic = args[1];
105       case 1:
106         broker = args[0];
107     }
108
109
110     SimpleConsumer instance = new SimpleConsumer(broker, topic, groupId, clientId);
111
112     Runtime.getRuntime().addShutdownHook(new Thread(() ->
113     {
114       instance.consumer.wakeup();
115
116       while (instance.running)
117       {
118         log.info("Waiting for main-thread...");
119         try
120         {
121           Thread.sleep(1000);
122         }
123         catch (InterruptedException e) {}
124       }
125       log.info("Shutdown completed.");
126     }));
127
128     log.info(
129         "Running SimpleConsumer: broker={}, topic={}, group-id={}, client-id={}",
130         broker,
131         topic,
132         groupId,
133         clientId);
134     instance.run();
135   }
136 }