Konsumption der Nachricht in eine separate Methode verlagert
[demos/kafka/training] / src / main / java / de / juplo / kafka / SimpleConsumer.java
1 package de.juplo.kafka;
2
3 import lombok.RequiredArgsConstructor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.consumer.Consumer;
6 import org.apache.kafka.clients.consumer.ConsumerRecord;
7 import org.apache.kafka.clients.consumer.ConsumerRecords;
8 import org.apache.kafka.common.errors.WakeupException;
9
10 import java.time.Duration;
11 import java.util.Arrays;
12
13
14 @Slf4j
15 @RequiredArgsConstructor
16 public class SimpleConsumer implements Runnable
17 {
18   private final String id;
19   private final String topic;
20   private final Consumer<String, String> consumer;
21
22   private long consumed = 0;
23
24
25   @Override
26   public void run()
27   {
28     try
29     {
30       log.info("{} - Subscribing to topic {}", id, topic);
31       consumer.subscribe(Arrays.asList(topic));
32
33       while (true)
34       {
35         ConsumerRecords<String, String> records =
36             consumer.poll(Duration.ofSeconds(1));
37
38         log.info("{} - Received {} messages", id, records.count());
39         for (ConsumerRecord<String, String> record : records)
40         {
41           handleRecord(
42             record.topic(),
43             record.partition(),
44             record.offset(),
45             record.key(),
46             record.value());
47         }
48       }
49     }
50     catch(WakeupException e)
51     {
52       log.info("{} - Consumer was signaled to finish its work", id);
53     }
54     catch(Exception e)
55     {
56       log.error("{} - Unexpected error: {}, unsubscribing!", id, e.toString());
57       consumer.unsubscribe();
58     }
59     finally
60     {
61       log.info("{} - Closing the KafkaConsumer", id);
62       consumer.close();
63       log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
64     }
65   }
66
67   private void handleRecord(
68     String topic,
69     Integer partition,
70     Long offset,
71     String key,
72     String value)
73   {
74     consumed++;
75     log.info("{} - {}: {}/{} - {}={}", id, offset, topic, partition, key, value);
76   }
77 }