From: Kai Moritz Date: Sun, 27 Oct 2024 12:38:47 +0000 (+0100) Subject: GET-Endpoint zum Abfragen der Schlüssel-Zählungen ergänzt X-Git-Tag: consumer/spring-consumer--log-compaction--2024-11-13--si~24 X-Git-Url: http://juplo.de/gitweb/?a=commitdiff_plain;h=d72b7b754699cbd0df8aeaa955730dbbeff6e88e;p=demos%2Fkafka%2Ftraining GET-Endpoint zum Abfragen der Schlüssel-Zählungen ergänzt * Zugriff auf die `counterMap` in `ExampleConsumer` synchronisiert. * `CounterStateController` kopiert die Map, um mögliche konkurierende Zugriffe während des Erzeugens der Ausgabe zu vermeiden. --- diff --git a/src/main/java/de/juplo/kafka/CounterStateController.java b/src/main/java/de/juplo/kafka/CounterStateController.java new file mode 100644 index 0000000..3d96582 --- /dev/null +++ b/src/main/java/de/juplo/kafka/CounterStateController.java @@ -0,0 +1,22 @@ +package de.juplo.kafka; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + + +@RestController +@RequiredArgsConstructor +public class CounterStateController +{ + private final ExampleConsumer consumer; + + @GetMapping + Map getAllCounters() + { + return new HashMap<>(consumer.getCounterState()); + } +} diff --git a/src/main/java/de/juplo/kafka/ExampleConsumer.java b/src/main/java/de/juplo/kafka/ExampleConsumer.java index 0ade38f..6767c6b 100644 --- a/src/main/java/de/juplo/kafka/ExampleConsumer.java +++ b/src/main/java/de/juplo/kafka/ExampleConsumer.java @@ -98,10 +98,19 @@ public class ExampleConsumer implements Runnable { consumed++; log.info("{} - {}: {}/{} - {}={}", id, offset, topic, partition, key, value); - Long counter = counterState.compute(key, (k, v) -> v == null ? 1l : v + 1); + Long counter = computeCount(key); log.info("{} - current value for counter {}: {}", id, key, counter); } + private synchronized Long computeCount(String key) + { + return counterState.compute(key, (k, v) -> v == null ? 1l : v + 1); + } + + public synchronized Map getCounterState() + { + return counterState; + } public void shutdown() throws InterruptedException {