|
| 1 | +package no.nav.vedtak.felles.integrasjon.kafka; |
| 2 | + |
| 3 | +import java.time.Duration; |
| 4 | +import java.time.LocalDateTime; |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.List; |
| 7 | +import java.util.concurrent.atomic.AtomicInteger; |
| 8 | +import java.util.function.BiConsumer; |
| 9 | +import java.util.stream.Collectors; |
| 10 | + |
| 11 | +import org.apache.kafka.clients.consumer.KafkaConsumer; |
| 12 | +import org.apache.kafka.common.errors.WakeupException; |
| 13 | + |
| 14 | +public class KafkaConsumerManager<K,V> { |
| 15 | + |
| 16 | + private static final Duration CLOSE_TIMEOUT = Duration.ofSeconds(10); |
| 17 | + |
| 18 | + private final List<KafkaMessageHandler<K,V>> handlers; |
| 19 | + private final List<KafkaConsumerLoop<K,V>> consumers = new ArrayList<>(); |
| 20 | + |
| 21 | + public KafkaConsumerManager(List<KafkaMessageHandler<K, V>> handlers) { |
| 22 | + this.handlers = handlers; |
| 23 | + } |
| 24 | + |
| 25 | + public void start(BiConsumer<String, Throwable> errorlogger) { |
| 26 | + consumers.addAll(handlers.stream().map(KafkaConsumerLoop::new).toList()); |
| 27 | + consumers.forEach(c -> { |
| 28 | + var ct = new Thread(c, "KC-" + c.handler().groupId()); |
| 29 | + ct.setUncaughtExceptionHandler((t, e) -> { errorlogger.accept(c.handler().topic(), e); stop(); }); |
| 30 | + ct.start(); |
| 31 | + }); |
| 32 | + Runtime.getRuntime().addShutdownHook(new Thread(new KafkaConsumerCloser<>(consumers))); |
| 33 | + } |
| 34 | + |
| 35 | + public void stop() { |
| 36 | + consumers.forEach(KafkaConsumerLoop::shutdown); |
| 37 | + var timeout = LocalDateTime.now().plus(CLOSE_TIMEOUT).plusSeconds(1); |
| 38 | + while (!allStopped() && LocalDateTime.now().isBefore(timeout)) { |
| 39 | + try { |
| 40 | + Thread.sleep(Duration.ofSeconds(1)); |
| 41 | + } catch (InterruptedException e) { |
| 42 | + Thread.currentThread().interrupt(); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + public boolean allRunning() { |
| 48 | + return consumers.stream().allMatch(KafkaConsumerLoop::isRunning); |
| 49 | + } |
| 50 | + |
| 51 | + public boolean allStopped() { |
| 52 | + return consumers.stream().allMatch(KafkaConsumerLoop::isStopped); |
| 53 | + } |
| 54 | + |
| 55 | + public String topicNames() { |
| 56 | + return handlers.stream().map(KafkaMessageHandler::topic).collect(Collectors.joining(",")); |
| 57 | + } |
| 58 | + |
| 59 | + private record KafkaConsumerCloser<K,V>(List<KafkaConsumerLoop<K,V>> consumers) implements Runnable { |
| 60 | + @Override |
| 61 | + public void run() { |
| 62 | + consumers.forEach(KafkaConsumerLoop::shutdown); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + public static class KafkaConsumerLoop<K,V> implements Runnable { |
| 67 | + |
| 68 | + private static final Duration POLL_TIMEOUT = Duration.ofMillis(100); |
| 69 | + private static final Duration CLOSE_TIMEOUT = Duration.ofSeconds(10); |
| 70 | + private enum ConsumerState { UNINITIALIZED, RUNNING, STOPPING, STOPPED } |
| 71 | + private static final int RUNNING = ConsumerState.RUNNING.hashCode(); |
| 72 | + |
| 73 | + private final KafkaMessageHandler<K, V> handler; |
| 74 | + private KafkaConsumer<K, V> consumer; |
| 75 | + private final AtomicInteger running = new AtomicInteger(ConsumerState.UNINITIALIZED.hashCode()); |
| 76 | + |
| 77 | + public KafkaConsumerLoop(KafkaMessageHandler<K,V> handler) { |
| 78 | + this.handler = handler; |
| 79 | + } |
| 80 | + @Override |
| 81 | + public void run() { |
| 82 | + try(var key = handler.keyDeserializer().get(); var value = handler.valueDeserializer().get()) { |
| 83 | + var props = KafkaProperties.forConsumerGenericValue(handler.groupId(), key, value, handler.autoOffsetReset()); |
| 84 | + consumer = new KafkaConsumer<>(props, key, value); |
| 85 | + consumer.subscribe(List.of(handler.topic())); |
| 86 | + running.set(RUNNING); |
| 87 | + while (running.get() == RUNNING) { |
| 88 | + var records = consumer.poll(POLL_TIMEOUT); |
| 89 | + // Hvis man vil komplisere ting så kan man håndtere både OffsetCommit og DBcommit i en Transcational handleRecords. |
| 90 | + // handleRecords må ta inn alle som er pollet (records) og 2 callbacks som a) legger til konsumert og b) commitAsync(konsumert) |
| 91 | + for (var record : records) { |
| 92 | + handler.handleRecord(record.key(), record.value()); |
| 93 | + } |
| 94 | + } |
| 95 | + } catch (WakeupException e) { |
| 96 | + // ignore for shutdown |
| 97 | + } finally { |
| 98 | + if (consumer != null) { |
| 99 | + consumer.close(CLOSE_TIMEOUT); |
| 100 | + } |
| 101 | + running.set(ConsumerState.STOPPED.hashCode()); |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + public void shutdown() { |
| 106 | + if (running.get() == RUNNING) { |
| 107 | + running.set(ConsumerState.STOPPING.hashCode()); |
| 108 | + } else { |
| 109 | + running.set(ConsumerState.STOPPED.hashCode()); |
| 110 | + } |
| 111 | + if (consumer != null) { |
| 112 | + consumer.wakeup(); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + public KafkaMessageHandler<K, V> handler() { |
| 117 | + return handler; |
| 118 | + } |
| 119 | + |
| 120 | + public boolean isRunning() { |
| 121 | + return running.get() == RUNNING; |
| 122 | + } |
| 123 | + |
| 124 | + public boolean isStopped() { |
| 125 | + return running.get() == ConsumerState.STOPPED.hashCode(); |
| 126 | + } |
| 127 | + } |
| 128 | +} |
0 commit comments