3a1665fa9f6245c867e7703efdd957874e3d0343
[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 USER_STORE_NAME = "users";
24         public static final String RANKING_STORE_NAME = "rankings";
25
26         public final KafkaStreams streams;
27         public final HostInfo hostInfo;
28         public final StoreQueryParameters<ReadOnlyKeyValueStore<String, UserRanking>> storeParameters;
29
30
31         public QueryStreamProcessor(
32                         Properties props,
33                         HostInfo applicationServer,
34                         String usersInputTopic,
35                         String rankingInputTopic,
36                         KeyValueBytesStoreSupplier userStoreSupplier,
37                         KeyValueBytesStoreSupplier rankingStoreSupplier)
38         {
39                 Topology topology = buildTopology(
40                                 usersInputTopic,
41                                 rankingInputTopic,
42                                 userStoreSupplier,
43                                 rankingStoreSupplier);
44                 streams = new KafkaStreams(topology, props);
45                 hostInfo = applicationServer;
46                 storeParameters = StoreQueryParameters.fromNameAndType(RANKING_STORE_NAME, QueryableStoreTypes.keyValueStore());;
47         }
48
49         static Topology buildTopology(
50                         String usersInputTopic,
51                         String rankingInputTopic,
52                         KeyValueBytesStoreSupplier userStoreSupplier,
53                         KeyValueBytesStoreSupplier rankingStoreSupplier)
54         {
55                 StreamsBuilder builder = new StreamsBuilder();
56
57                 KTable<String, User> users = builder
58                                 .stream(
59                                                 usersInputTopic,
60                                                 Consumed.with(Serdes.String(), new JsonSerde().copyWithType(User.class)))
61                                 .toTable(
62                                                 Materialized
63                                                                 .<String, User>as(userStoreSupplier)
64                                                                 .withKeySerde(Serdes.String())
65                                                                 .withValueSerde(new JsonSerde().copyWithType(User.class)));
66                 KStream<String, Ranking> rankings = builder
67                                 .<Key, Ranking>stream(rankingInputTopic)
68                                 .map((key, value) -> new KeyValue<>(key.getUsername(), value));
69
70                 rankings
71                                 .join(users, (ranking, user) -> UserRanking.of(
72                                                 user.getFirstName(),
73                                                 user.getLastName(),
74                                                 ranking.getEntries()),
75                                                 Joined.keySerde(Serdes.String()))
76                                 .toTable(
77                                                 Materialized
78                                                                 .<String, UserRanking>as(rankingStoreSupplier)
79                                                                 .withKeySerde(Serdes.String())
80                                                                 .withValueSerde(new JsonSerde().copyWithType(UserRanking.class)));
81
82                 Topology topology = builder.build();
83                 log.info("\n\n{}", topology.describe());
84
85                 return topology;
86         }
87
88         ReadOnlyKeyValueStore<String, UserRanking> getStore()
89         {
90                 return streams.store(storeParameters);
91         }
92
93         public Optional<URI> getRedirect(String username)
94         {
95                 KeyQueryMetadata metadata = streams.queryMetadataForKey(RANKING_STORE_NAME, username, Serdes.String().serializer());
96                 HostInfo activeHost = metadata.activeHost();
97                 log.debug("Local store for {}: {}, {}:{}", username, metadata.partition(), activeHost.host(), activeHost.port());
98
99                 if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
100                 {
101                         return Optional.empty();
102                 }
103
104                 URI location = URI.create("http://" + activeHost.host() + ":" + activeHost.port() + "/" + username);
105                 log.debug("Redirecting to {}", location);
106                 return Optional.of(location);
107         }
108
109         public Optional<UserRanking> getUserRanking(String username)
110         {
111                 return Optional.ofNullable(getStore().get(username));
112         }
113
114         @PostConstruct
115         public void start()
116         {
117                 log.info("Starting Stream-Processor");
118                 streams.start();
119         }
120
121         @PreDestroy
122         public void stop()
123         {
124                 log.info("Stopping Stream-Processor");
125                 streams.close();
126         }
127 }