import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.RecordDeserializationException;
import org.apache.kafka.common.errors.WakeupException;
import javax.annotation.PreDestroy;
@Slf4j
@RequiredArgsConstructor
-public class EndlessConsumer implements Runnable
+public class EndlessConsumer<K, V> implements Runnable
{
private final ExecutorService executor;
private final String id;
private final String topic;
- private final Consumer<String, String> consumer;
- private final java.util.function.Consumer<ConsumerRecord<String, String>> handler;
+ private final Consumer<K, V> consumer;
+ private final java.util.function.Consumer<ConsumerRecord<K, V>> handler;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
while (true)
{
- ConsumerRecords<String, String> records =
+ ConsumerRecords<K, V> records =
consumer.poll(Duration.ofSeconds(1));
// Do something with the data...
log.info("{} - Received {} messages", id, records.count());
- for (ConsumerRecord<String, String> record : records)
+ for (ConsumerRecord<K, V> record : records)
{
log.info(
"{} - {}: {}/{} - {}={}",
consumed++;
Integer partition = record.partition();
- String key = record.key() == null ? "NULL" : record.key();
+ String key = record.key() == null ? "NULL" : record.key().toString();
Map<String, Long> byKey = seen.get(partition);
if (!byKey.containsKey(key))
consumer.commitSync();
shutdown();
}
+ catch(RecordDeserializationException e)
+ {
+ TopicPartition tp = e.topicPartition();
+ long offset = e.offset();
+ log.error(
+ "{} - Could not deserialize message on topic {} with offset={}: {}",
+ id,
+ tp,
+ offset,
+ e.getCause().toString());
+
+ consumer.commitSync();
+ shutdown(e);
+ }
catch(Exception e)
{
log.error("{} - Unexpected error: {}", id, e.toString(), e);