1 package de.juplo.kafka.wordcount.query;
3 import com.fasterxml.jackson.core.JsonProcessingException;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import lombok.extern.slf4j.Slf4j;
6 import org.apache.kafka.clients.consumer.ConsumerConfig;
7 import org.apache.kafka.common.serialization.Serdes;
8 import org.apache.kafka.streams.*;
9 import org.apache.kafka.streams.kstream.KStream;
10 import org.apache.kafka.streams.kstream.KTable;
11 import org.apache.kafka.streams.kstream.Materialized;
12 import org.apache.kafka.streams.state.HostInfo;
13 import org.apache.kafka.streams.state.QueryableStoreTypes;
14 import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
15 import org.springframework.boot.SpringApplication;
16 import org.springframework.context.ConfigurableApplicationContext;
17 import org.springframework.stereotype.Component;
19 import javax.annotation.PostConstruct;
20 import javax.annotation.PreDestroy;
22 import java.util.Optional;
23 import java.util.Properties;
24 import java.util.concurrent.CompletableFuture;
26 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
31 public class QueryStreamProcessor
33 public final KafkaStreams streams;
34 public final HostInfo hostInfo;
35 public final String storeName = "rankingsByUsername";
36 public final StoreQueryParameters<ReadOnlyKeyValueStore<String, String>> storeParameters;
37 public final ObjectMapper mapper;
40 public QueryStreamProcessor(
41 QueryApplicationProperties properties,
43 ConfigurableApplicationContext context)
45 StreamsBuilder builder = new StreamsBuilder();
47 KTable<String, String> users = builder.table(properties.getUsersInputTopic());
48 KStream<String, String> rankings = builder.stream(properties.getRankingInputTopic());
51 .join(users, (rankingJson, userJson) ->
55 Ranking ranking = mapper.readValue(rankingJson, Ranking.class);
56 User user = mapper.readValue(userJson, User.class);
58 return mapper.writeValueAsString(
62 ranking.getEntries()));
64 catch (JsonProcessingException e)
66 throw new RuntimeException(e);
69 .toTable(Materialized.as(storeName));
71 Properties props = new Properties();
72 props.put(StreamsConfig.APPLICATION_ID_CONFIG, properties.getApplicationId());
73 props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, properties.getApplicationServer());
74 props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServer());
75 props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
76 props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
77 props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
79 streams = new KafkaStreams(builder.build(), props);
80 streams.setUncaughtExceptionHandler((Throwable e) ->
82 log.error("Unexpected error!", e);
83 CompletableFuture.runAsync(() ->
85 log.info("Stopping application...");
86 SpringApplication.exit(context, () -> 1);
88 return SHUTDOWN_CLIENT;
91 hostInfo = HostInfo.buildFromEndpoint(properties.getApplicationServer());
92 storeParameters = StoreQueryParameters.fromNameAndType(storeName, QueryableStoreTypes.keyValueStore());;
96 public Optional<URI> getRedirect(String username)
98 KeyQueryMetadata metadata = streams.queryMetadataForKey(storeName, username, Serdes.String().serializer());
99 HostInfo activeHost = metadata.activeHost();
100 log.debug("Local store for {}: {}, {}:{}", username, metadata.partition(), activeHost.host(), activeHost.port());
102 if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
104 return Optional.empty();
107 URI location = URI.create("http://" + activeHost.host() + ":" + activeHost.port() + "/" + username);
108 log.debug("Redirecting to {}", location);
109 return Optional.of(location);
112 public Optional<UserRanking> getUserRanking(String username)
116 .ofNullable(streams.store(storeParameters).get(username))
121 return mapper.readValue(json, UserRanking.class);
123 catch (JsonProcessingException e)
125 throw new RuntimeException(e);
133 log.info("Starting Stream-Processor");
140 log.info("Stopping Stream-Processor");