query: 2.0.0 - Values are serialized as JSON
[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.KStream;
9 import org.apache.kafka.streams.kstream.KTable;
10 import org.apache.kafka.streams.kstream.Materialized;
11 import org.apache.kafka.streams.state.HostInfo;
12 import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier;
13 import org.apache.kafka.streams.state.QueryableStoreTypes;
14 import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
15 import org.springframework.kafka.support.serializer.JsonSerde;
16
17 import java.net.URI;
18 import java.util.Optional;
19 import java.util.Properties;
20
21
22 @Slf4j
23 public class QueryStreamProcessor
24 {
25         public static final String STORE_NAME = "rankings-by-username";
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 storeSupplier)
38         {
39                 Topology topology = buildTopology(
40                                 usersInputTopic,
41                                 rankingInputTopic,
42                                 storeSupplier);
43                 streams = new KafkaStreams(topology, props);
44                 hostInfo = applicationServer;
45                 storeParameters = StoreQueryParameters.fromNameAndType(STORE_NAME, QueryableStoreTypes.keyValueStore());;
46         }
47
48         static Topology buildTopology(
49                         String usersInputTopic,
50                         String rankingInputTopic,
51                         KeyValueBytesStoreSupplier storeSupplier)
52         {
53                 StreamsBuilder builder = new StreamsBuilder();
54
55                 KTable<String, User> users = builder
56                                 .stream(usersInputTopic)
57                                 .toTable(Materialized.with(null, new JsonSerde().copyWithType(User.class)));
58                 KStream<String, Ranking> rankings = builder.stream(rankingInputTopic);
59
60                 rankings
61                                 .join(users, (ranking, user) -> UserRanking.of(
62                                                 user.getFirstName(),
63                                                 user.getLastName(),
64                                                 ranking.getEntries()))
65                                 .toTable(
66                                                 Materialized
67                                                                 .<String, UserRanking>as(storeSupplier)
68                                                                 .withValueSerde(new JsonSerde().copyWithType(UserRanking.class)));
69
70                 Topology topology = builder.build();
71                 log.info("\n\n{}", topology.describe());
72
73                 return topology;
74         }
75
76         ReadOnlyKeyValueStore<String, UserRanking> getStore()
77         {
78                 return streams.store(storeParameters);
79         }
80
81         public Optional<URI> getRedirect(String username)
82         {
83                 KeyQueryMetadata metadata = streams.queryMetadataForKey(STORE_NAME, username, Serdes.String().serializer());
84                 HostInfo activeHost = metadata.activeHost();
85                 log.debug("Local store for {}: {}, {}:{}", username, metadata.partition(), activeHost.host(), activeHost.port());
86
87                 if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
88                 {
89                         return Optional.empty();
90                 }
91
92                 URI location = URI.create("http://" + activeHost.host() + ":" + activeHost.port() + "/" + username);
93                 log.debug("Redirecting to {}", location);
94                 return Optional.of(location);
95         }
96
97         public Optional<UserRanking> getUserRanking(String username)
98         {
99                 return Optional.ofNullable(getStore().get(username));
100         }
101
102         @PostConstruct
103         public void start()
104         {
105                 log.info("Starting Stream-Processor");
106                 streams.start();
107         }
108
109         @PreDestroy
110         public void stop()
111         {
112                 log.info("Stopping Stream-Processor");
113                 streams.close();
114         }
115 }