c7bc852ccf53e0a3e12c9216dae13e0b257b5f49
[demos/kafka/training] / src / main / java / de / juplo / kafka / EndlessConsumer.java
1 package de.juplo.kafka;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
5 import org.apache.kafka.clients.consumer.ConsumerRecord;
6 import org.apache.kafka.clients.consumer.ConsumerRecords;
7 import org.apache.kafka.clients.consumer.KafkaConsumer;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.errors.WakeupException;
10 import org.apache.kafka.common.serialization.StringDeserializer;
11
12 import javax.annotation.PreDestroy;
13 import java.time.Duration;
14 import java.util.*;
15 import java.util.concurrent.ExecutionException;
16 import java.util.concurrent.ExecutorService;
17 import java.util.concurrent.Future;
18 import java.util.concurrent.atomic.AtomicBoolean;
19
20
21 @Slf4j
22 public class EndlessConsumer implements Runnable
23 {
24   private final ExecutorService executor;
25   private final String bootstrapServer;
26   private final String groupId;
27   private final String id;
28   private final String topic;
29   private final String autoOffsetReset;
30
31   private AtomicBoolean running = new AtomicBoolean();
32   private long consumed = 0;
33   private KafkaConsumer<String, String> consumer = null;
34   private Future<?> future = null;
35
36   private final Map<TopicPartition, PartitionStatistics> seen = new HashMap<>();
37
38
39   public EndlessConsumer(
40       ExecutorService executor,
41       String bootstrapServer,
42       String groupId,
43       String clientId,
44       String topic,
45       String autoOffsetReset)
46   {
47     this.executor = executor;
48     this.bootstrapServer = bootstrapServer;
49     this.groupId = groupId;
50     this.id = clientId;
51     this.topic = topic;
52     this.autoOffsetReset = autoOffsetReset;
53   }
54
55   @Override
56   public void run()
57   {
58     try
59     {
60       Properties props = new Properties();
61       props.put("bootstrap.servers", bootstrapServer);
62       props.put("group.id", groupId);
63       props.put("client.id", id);
64       props.put("auto.offset.reset", autoOffsetReset);
65       props.put("metadata.max.age.ms", "1000");
66       props.put("key.deserializer", StringDeserializer.class.getName());
67       props.put("value.deserializer", StringDeserializer.class.getName());
68
69       this.consumer = new KafkaConsumer<>(props);
70
71       log.info("{} - Subscribing to topic {}", id, topic);
72       consumer.subscribe(Arrays.asList(topic), new ConsumerRebalanceListener()
73       {
74         @Override
75         public void onPartitionsRevoked(Collection<TopicPartition> partitions)
76         {
77           partitions.forEach(tp ->
78           {
79             log.info("{} - removing partition: {}", id, tp);
80             PartitionStatistics removed = seen.remove(tp);
81             for (KeyCounter counter : removed.getStatistics())
82             {
83               log.info(
84                   "{} - Seen {} messages for partition={}|key={}",
85                   id,
86                   counter.getResult(),
87                   removed.getPartition(),
88                   counter.getKey());
89             }
90           });
91         }
92
93         @Override
94         public void onPartitionsAssigned(Collection<TopicPartition> partitions)
95         {
96           partitions.forEach(tp ->
97           {
98             log.info("{} - adding partition: {}", id, tp);
99             seen.put(tp, new PartitionStatistics(tp));
100           });
101         }
102       });
103
104       while (true)
105       {
106         ConsumerRecords<String, String> records =
107             consumer.poll(Duration.ofSeconds(1));
108
109         // Do something with the data...
110         log.info("{} - Received {} messages", id, records.count());
111         for (ConsumerRecord<String, String> record : records)
112         {
113           consumed++;
114           log.info(
115               "{} - {}: {}/{} - {}={}",
116               id,
117               record.offset(),
118               record.topic(),
119               record.partition(),
120               record.key(),
121               record.value()
122           );
123
124           TopicPartition partition = new TopicPartition(record.topic(), record.partition());
125           String key = record.key() == null ? "NULL" : record.key();
126           seen.get(partition).increment(key);
127         }
128       }
129     }
130     catch(WakeupException e)
131     {
132       log.info("{} - RIIING!", id);
133     }
134     catch(Exception e)
135     {
136       log.error("{} - Unexpected error: {}", id, e.toString(), e);
137       running.set(false); // Mark the instance as not running
138     }
139     finally
140     {
141       log.info("{} - Closing the KafkaConsumer", id);
142       consumer.close();
143       log.info("{} - Consumer-Thread exiting", id);
144     }
145   }
146
147   public Map<TopicPartition, PartitionStatistics> getSeen()
148   {
149     return seen;
150   }
151
152   public synchronized void start()
153   {
154     boolean stateChanged = running.compareAndSet(false, true);
155     if (!stateChanged)
156       throw new RuntimeException("Consumer instance " + id + " is already running!");
157
158     log.info("{} - Starting - consumed {} messages before", id, consumed);
159     future = executor.submit(this);
160   }
161
162   public synchronized void stop() throws ExecutionException, InterruptedException
163   {
164     boolean stateChanged = running.compareAndSet(true, false);
165     if (!stateChanged)
166       throw new RuntimeException("Consumer instance " + id + " is not running!");
167
168     log.info("{} - Stopping", id);
169     consumer.wakeup();
170     future.get();
171     log.info("{} - Stopped - consumed {} messages so far", id, consumed);
172   }
173
174   @PreDestroy
175   public void destroy() throws ExecutionException, InterruptedException
176   {
177     log.info("{} - Destroy!", id);
178     try
179     {
180       stop();
181     }
182     catch (IllegalStateException e)
183     {
184       log.info("{} - Was already stopped", id);
185     }
186     finally
187     {
188       log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
189     }
190   }
191 }