package de.juplo.kafka.wordcount.query;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
+import jakarta.annotation.PostConstruct;
+import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
-import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.*;
+import org.apache.kafka.streams.kstream.Consumed;
+import org.apache.kafka.streams.kstream.KStream;
+import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.state.HostInfo;
+import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
import org.apache.kafka.streams.state.QueryableStoreTypes;
import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
-import org.springframework.boot.SpringApplication;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.stereotype.Component;
+import org.springframework.kafka.support.serializer.JsonSerde;
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
import java.net.URI;
import java.util.Optional;
import java.util.Properties;
-import java.util.concurrent.CompletableFuture;
-
-import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
@Slf4j
-@Component
public class QueryStreamProcessor
{
+ public static final String USER_STORE_NAME = "users";
+ public static final String RANKING_STORE_NAME = "rankings";
+
public final KafkaStreams streams;
public final HostInfo hostInfo;
- public final String storeName = "rankingsByUsername";
- public final StoreQueryParameters<ReadOnlyKeyValueStore<String, String>> storeParameters;
- public final ObjectMapper mapper;
+ public final StoreQueryParameters<ReadOnlyKeyValueStore<String, UserRanking>> storeParameters;
public QueryStreamProcessor(
- QueryApplicationProperties properties,
- ObjectMapper mapper,
- ConfigurableApplicationContext context)
+ Properties props,
+ HostInfo applicationServer,
+ String usersInputTopic,
+ String rankingInputTopic,
+ KeyValueBytesStoreSupplier userStoreSupplier,
+ KeyValueBytesStoreSupplier rankingStoreSupplier)
{
- StreamsBuilder builder = new StreamsBuilder();
+ Topology topology = buildTopology(
+ usersInputTopic,
+ rankingInputTopic,
+ userStoreSupplier,
+ rankingStoreSupplier);
+ streams = new KafkaStreams(topology, props);
+ hostInfo = applicationServer;
+ storeParameters = StoreQueryParameters.fromNameAndType(RANKING_STORE_NAME, QueryableStoreTypes.keyValueStore());;
+ }
- builder.table(properties.getRankingInputTopic(), Materialized.as(storeName));
+ static Topology buildTopology(
+ String usersInputTopic,
+ String rankingInputTopic,
+ KeyValueBytesStoreSupplier userStoreSupplier,
+ KeyValueBytesStoreSupplier rankingStoreSupplier)
+ {
+ StreamsBuilder builder = new StreamsBuilder();
- Properties props = new Properties();
- props.put(StreamsConfig.APPLICATION_ID_CONFIG, properties.getApplicationId());
- props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, properties.getApplicationServer());
- props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServer());
- props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
- props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
- props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+ KTable<String, User> users = builder
+ .stream(
+ usersInputTopic,
+ Consumed.with(null, new JsonSerde().copyWithType(User.class)))
+ .toTable(
+ Materialized
+ .<String, User>as(userStoreSupplier)
+ .withKeySerde(Serdes.String())
+ .withValueSerde(new JsonSerde().copyWithType(User.class)));
+ KStream<String, Ranking> rankings = builder.stream(rankingInputTopic);
+
+ rankings
+ .join(users, (ranking, user) -> UserRanking.of(
+ user.getFirstName(),
+ user.getLastName(),
+ ranking.getEntries()))
+ .toTable(
+ Materialized
+ .<String, UserRanking>as(rankingStoreSupplier)
+ .withValueSerde(new JsonSerde().copyWithType(UserRanking.class)));
+
+ Topology topology = builder.build();
+ log.info("\n\n{}", topology.describe());
+
+ return topology;
+ }
- streams = new KafkaStreams(builder.build(), props);
- streams.setUncaughtExceptionHandler((Throwable e) ->
- {
- log.error("Unexpected error!", e);
- CompletableFuture.runAsync(() ->
- {
- log.info("Stopping application...");
- SpringApplication.exit(context, () -> 1);
- });
- return SHUTDOWN_CLIENT;
- });
-
- hostInfo = HostInfo.buildFromEndpoint(properties.getApplicationServer());
- storeParameters = StoreQueryParameters.fromNameAndType(storeName, QueryableStoreTypes.keyValueStore());;
- this.mapper = mapper;
+ ReadOnlyKeyValueStore<String, UserRanking> getStore()
+ {
+ return streams.store(storeParameters);
}
public Optional<URI> getRedirect(String username)
{
- KeyQueryMetadata metadata = streams.queryMetadataForKey(storeName, username, Serdes.String().serializer());
+ KeyQueryMetadata metadata = streams.queryMetadataForKey(RANKING_STORE_NAME, username, Serdes.String().serializer());
HostInfo activeHost = metadata.activeHost();
log.debug("Local store for {}: {}, {}:{}", username, metadata.partition(), activeHost.host(), activeHost.port());
- if (activeHost.equals(this.hostInfo))
+ if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
{
return Optional.empty();
}
return Optional.of(location);
}
- public Optional<Ranking> getRanking(String username)
+ public Optional<UserRanking> getUserRanking(String username)
{
- return
- Optional
- .ofNullable(streams.store(storeParameters).get(username))
- .map(json ->
- {
- try
- {
- return mapper.readValue(json, Ranking.class);
- }
- catch (JsonProcessingException e)
- {
- throw new RuntimeException(e);
- }
- });
+ return Optional.ofNullable(getStore().get(username));
}
@PostConstruct