5543a9103e1b6f102fbbf2b2c813a21c48cabe56
[demos/kafka/wordcount] / src / main / java / de / juplo / kafka / wordcount / query / QueryStreamProcessor.java
1 package de.juplo.kafka.wordcount.query;
2
3 import jakarta.annotation.PostConstruct;
4 import jakarta.annotation.PreDestroy;
5 import lombok.extern.slf4j.Slf4j;
6 import org.apache.kafka.common.serialization.Serdes;
7 import org.apache.kafka.streams.*;
8 import org.apache.kafka.streams.kstream.*;
9 import org.apache.kafka.streams.state.HostInfo;
10 import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
11 import org.apache.kafka.streams.state.QueryableStoreTypes;
12 import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
13 import org.springframework.kafka.support.serializer.JsonSerde;
14
15 import java.net.URI;
16 import java.util.Optional;
17 import java.util.Properties;
18
19
20 @Slf4j
21 public class QueryStreamProcessor
22 {
23         public static final String STATS_TYPE = "COUNTER";
24         public static final String USER_STORE_NAME = "users";
25         public static final String RANKING_STORE_NAME = "rankings";
26
27         public final KafkaStreams streams;
28         public final HostInfo hostInfo;
29         public final StoreQueryParameters<ReadOnlyKeyValueStore<String, UserRanking>> storeParameters;
30
31
32         public QueryStreamProcessor(
33                         Properties props,
34                         HostInfo applicationServer,
35                         String usersInputTopic,
36                         String rankingInputTopic,
37                         KeyValueBytesStoreSupplier userStoreSupplier,
38                         KeyValueBytesStoreSupplier rankingStoreSupplier)
39         {
40                 Topology topology = buildTopology(
41                                 usersInputTopic,
42                                 rankingInputTopic,
43                                 userStoreSupplier,
44                                 rankingStoreSupplier);
45                 streams = new KafkaStreams(topology, props);
46                 hostInfo = applicationServer;
47                 storeParameters = StoreQueryParameters.fromNameAndType(RANKING_STORE_NAME, QueryableStoreTypes.keyValueStore());;
48         }
49
50         static Topology buildTopology(
51                         String usersInputTopic,
52                         String rankingInputTopic,
53                         KeyValueBytesStoreSupplier userStoreSupplier,
54                         KeyValueBytesStoreSupplier rankingStoreSupplier)
55         {
56                 StreamsBuilder builder = new StreamsBuilder();
57
58                 KTable<String, User> users = builder
59                                 .stream(
60                                                 usersInputTopic,
61                                                 Consumed.with(Serdes.String(), new JsonSerde().copyWithType(User.class)))
62                                 .toTable(
63                                                 Materialized
64                                                                 .<String, User>as(userStoreSupplier)
65                                                                 .withKeySerde(Serdes.String())
66                                                                 .withValueSerde(new JsonSerde().copyWithType(User.class)));
67                 KStream<String, Ranking> rankings = builder
68                                 .<Key, Ranking>stream(rankingInputTopic)
69                                 .filter((key, value) -> STATS_TYPE.equals(key.getType()))
70                                 .map((key, value) -> new KeyValue<>(key.getChannel(), value));
71
72                 rankings
73                                 .join(users, (ranking, user) -> UserRanking.of(
74                                                 user.getFirstName(),
75                                                 user.getLastName(),
76                                                 ranking.getEntries()),
77                                                 Joined.keySerde(Serdes.String()))
78                                 .toTable(
79                                                 Materialized
80                                                                 .<String, UserRanking>as(rankingStoreSupplier)
81                                                                 .withKeySerde(Serdes.String())
82                                                                 .withValueSerde(new JsonSerde().copyWithType(UserRanking.class)));
83
84                 Topology topology = builder.build();
85                 log.info("\n\n{}", topology.describe());
86
87                 return topology;
88         }
89
90         ReadOnlyKeyValueStore<String, UserRanking> getStore()
91         {
92                 return streams.store(storeParameters);
93         }
94
95         public Optional<URI> getRedirect(String username)
96         {
97                 KeyQueryMetadata metadata = streams.queryMetadataForKey(RANKING_STORE_NAME, username, Serdes.String().serializer());
98                 HostInfo activeHost = metadata.activeHost();
99                 log.debug("Local store for {}: {}, {}:{}", username, metadata.partition(), activeHost.host(), activeHost.port());
100
101                 if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
102                 {
103                         return Optional.empty();
104                 }
105
106                 URI location = URI.create("http://" + activeHost.host() + ":" + activeHost.port() + "/" + username);
107                 log.debug("Redirecting to {}", location);
108                 return Optional.of(location);
109         }
110
111         public Optional<UserRanking> getUserRanking(String username)
112         {
113                 return Optional.ofNullable(getStore().get(username));
114         }
115
116         @PostConstruct
117         public void start()
118         {
119                 log.info("Starting Stream-Processor");
120                 streams.start();
121         }
122
123         @PreDestroy
124         public void stop()
125         {
126                 log.info("Stopping Stream-Processor");
127                 streams.close();
128         }
129 }