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