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;
18 import javax.annotation.PostConstruct;
19 import javax.annotation.PreDestroy;
21 import java.util.Optional;
22 import java.util.Properties;
23 import java.util.concurrent.CompletableFuture;
25 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
29 public class QueryStreamProcessor
31 public final KafkaStreams streams;
32 public final HostInfo hostInfo;
33 public final String storeName = "rankingsByUsername";
34 public final StoreQueryParameters<ReadOnlyKeyValueStore<String, String>> storeParameters;
35 public final ObjectMapper mapper;
38 public QueryStreamProcessor(
40 HostInfo applicationServer,
41 String bootstrapServer,
42 String usersInputTopic,
43 String rankingInputTopic,
45 ConfigurableApplicationContext context)
47 StreamsBuilder builder = new StreamsBuilder();
49 KTable<String, String> users = builder.table(usersInputTopic);
50 KStream<String, String> rankings = builder.stream(rankingInputTopic);
53 .join(users, (rankingJson, userJson) ->
57 Ranking ranking = mapper.readValue(rankingJson, Ranking.class);
58 User user = mapper.readValue(userJson, User.class);
60 return mapper.writeValueAsString(
64 ranking.getEntries()));
66 catch (JsonProcessingException e)
68 throw new RuntimeException(e);
71 .toTable(Materialized.as(storeName));
73 Properties props = new Properties();
74 props.put(StreamsConfig.APPLICATION_ID_CONFIG, applicationId);
75 props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, applicationServer.host() + ":" + applicationServer.port());
76 props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer);
77 props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
78 props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
79 props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
81 streams = new KafkaStreams(builder.build(), props);
82 streams.setUncaughtExceptionHandler((Throwable e) ->
84 log.error("Unexpected error!", e);
85 CompletableFuture.runAsync(() ->
87 log.info("Stopping application...");
88 SpringApplication.exit(context, () -> 1);
90 return SHUTDOWN_CLIENT;
93 hostInfo = applicationServer;
94 storeParameters = StoreQueryParameters.fromNameAndType(storeName, QueryableStoreTypes.keyValueStore());;
98 public Optional<URI> getRedirect(String username)
100 KeyQueryMetadata metadata = streams.queryMetadataForKey(storeName, username, Serdes.String().serializer());
101 HostInfo activeHost = metadata.activeHost();
102 log.debug("Local store for {}: {}, {}:{}", username, metadata.partition(), activeHost.host(), activeHost.port());
104 if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
106 return Optional.empty();
109 URI location = URI.create("http://" + activeHost.host() + ":" + activeHost.port() + "/" + username);
110 log.debug("Redirecting to {}", location);
111 return Optional.of(location);
114 public Optional<UserRanking> getUserRanking(String username)
118 .ofNullable(streams.store(storeParameters).get(username))
123 return mapper.readValue(json, UserRanking.class);
125 catch (JsonProcessingException e)
127 throw new RuntimeException(e);
135 log.info("Starting Stream-Processor");
142 log.info("Stopping Stream-Processor");