query: 1.0.3 - application.server is derived from the local address
[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 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;
17
18 import javax.annotation.PostConstruct;
19 import javax.annotation.PreDestroy;
20 import java.net.URI;
21 import java.util.Optional;
22 import java.util.Properties;
23 import java.util.concurrent.CompletableFuture;
24
25 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
26
27
28 @Slf4j
29 public class QueryStreamProcessor
30 {
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;
36
37
38         public QueryStreamProcessor(
39                         String applicationId,
40                         HostInfo applicationServer,
41                         String bootstrapServer,
42                         String usersInputTopic,
43                         String rankingInputTopic,
44                         ObjectMapper mapper,
45                         ConfigurableApplicationContext context)
46         {
47                 StreamsBuilder builder = new StreamsBuilder();
48
49                 KTable<String, String> users = builder.table(usersInputTopic);
50                 KStream<String, String> rankings = builder.stream(rankingInputTopic);
51
52                 rankings
53                                 .join(users, (rankingJson, userJson) ->
54                                 {
55                                         try
56                                         {
57                                                 Ranking ranking = mapper.readValue(rankingJson, Ranking.class);
58                                                 User user = mapper.readValue(userJson, User.class);
59
60                                                 return mapper.writeValueAsString(
61                                                                 UserRanking.of(
62                                                                                 user.getFirstName(),
63                                                                                 user.getLastName(),
64                                                                                 ranking.getEntries()));
65                                         }
66                                         catch (JsonProcessingException e)
67                                         {
68                                                 throw new RuntimeException(e);
69                                         }
70                                 })
71                                 .toTable(Materialized.as(storeName));
72
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");
80
81                 streams = new KafkaStreams(builder.build(), props);
82                 streams.setUncaughtExceptionHandler((Throwable e) ->
83                 {
84                         log.error("Unexpected error!", e);
85                         CompletableFuture.runAsync(() ->
86                         {
87                                 log.info("Stopping application...");
88                                 SpringApplication.exit(context, () -> 1);
89                         });
90                         return SHUTDOWN_CLIENT;
91                 });
92
93                 hostInfo = applicationServer;
94                 storeParameters = StoreQueryParameters.fromNameAndType(storeName, QueryableStoreTypes.keyValueStore());;
95                 this.mapper = mapper;
96         }
97
98         public Optional<URI> getRedirect(String username)
99         {
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());
103
104                 if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
105                 {
106                         return Optional.empty();
107                 }
108
109                 URI location = URI.create("http://" + activeHost.host() + ":" + activeHost.port() + "/" + username);
110                 log.debug("Redirecting to {}", location);
111                 return Optional.of(location);
112         }
113
114         public Optional<UserRanking> getUserRanking(String username)
115         {
116                 return
117                                 Optional
118                                                 .ofNullable(streams.store(storeParameters).get(username))
119                                                 .map(json ->
120                                                 {
121                                                         try
122                                                         {
123                                                                 return mapper.readValue(json, UserRanking.class);
124                                                         }
125                                                         catch (JsonProcessingException e)
126                                                         {
127                                                                 throw new RuntimeException(e);
128                                                         }
129                                                 });
130         }
131
132         @PostConstruct
133         public void start()
134         {
135                 log.info("Starting Stream-Processor");
136                 streams.start();
137         }
138
139         @PreDestroy
140         public void stop()
141         {
142                 log.info("Stopping Stream-Processor");
143                 streams.close();
144         }
145 }