import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.common.errors.WakeupException;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
private final String topic;
private final KafkaConsumer<String, String> consumer;
+ private volatile boolean running = false;
private long consumed = 0;
- private volatile boolean running = true;
- private volatile boolean done = false;
public SimpleConsumer(String broker, String topic, String groupId, String clientId)
{
{
log.info("{} - Subscribing to topic test", id);
consumer.subscribe(Arrays.asList("test"));
+ running = true;
- while (running)
+ while (true)
{
ConsumerRecords<String, String> records =
consumer.poll(Duration.ofSeconds(1));
}
}
}
+ catch(WakeupException e)
+ {
+ log.info("{} - Consumer was signaled to finish its work", id);
+ }
catch(Exception e)
{
log.error("{} - Unexpected error: {}", id, e.toString());
}
finally
{
+ running = false;
log.info("{} - Closing the KafkaConsumer", id);
consumer.close();
log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
- done = true;
}
}
Runtime.getRuntime().addShutdownHook(new Thread(() ->
{
- instance.running = false;
- while (!instance.done)
+ instance.consumer.wakeup();
+
+ while (instance.running)
{
log.info("Waiting for main-thread...");
try