users:1.0.3 - application.server is derived from the local address
[demos/kafka/wordcount] / src / main / java / de / juplo / kafka / wordcount / users / UsersStreamProcessor.java
1 package de.juplo.kafka.wordcount.users;
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.Materialized;
10 import org.apache.kafka.streams.state.HostInfo;
11 import org.apache.kafka.streams.state.QueryableStoreTypes;
12 import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
13 import org.springframework.boot.SpringApplication;
14 import org.springframework.context.ConfigurableApplicationContext;
15
16 import javax.annotation.PostConstruct;
17 import javax.annotation.PreDestroy;
18 import java.net.URI;
19 import java.util.Optional;
20 import java.util.Properties;
21 import java.util.concurrent.CompletableFuture;
22
23 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
24
25
26 @Slf4j
27 public class UsersStreamProcessor
28 {
29         public final KafkaStreams streams;
30         public final HostInfo hostInfo;
31         public final String storeName = "rankingsByUsername";
32         public final StoreQueryParameters<ReadOnlyKeyValueStore<String, String>> storeParameters;
33         public final ObjectMapper mapper;
34
35
36         public UsersStreamProcessor(
37                         String applicationId,
38                         HostInfo applicationServer,
39                         String bootstrapServer,
40                         String topic,
41                         ObjectMapper mapper,
42                         ConfigurableApplicationContext context)
43         {
44                 StreamsBuilder builder = new StreamsBuilder();
45                 builder.table(topic, Materialized.as(storeName));
46
47                 Properties props = new Properties();
48                 props.put(StreamsConfig.APPLICATION_ID_CONFIG, applicationId);
49                 props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, applicationServer.host() + ":" + applicationServer.port());
50                 props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer);
51                 props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
52                 props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
53                 props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
54
55                 streams = new KafkaStreams(builder.build(), props);
56                 streams.setUncaughtExceptionHandler((Throwable e) ->
57                 {
58                         log.error("Unexpected error!", e);
59                         CompletableFuture.runAsync(() ->
60                         {
61                                 log.info("Stopping application...");
62                                 SpringApplication.exit(context, () -> 1);
63                         });
64                         return SHUTDOWN_CLIENT;
65                 });
66
67                 hostInfo = applicationServer;
68                 storeParameters = StoreQueryParameters.fromNameAndType(storeName, QueryableStoreTypes.keyValueStore());;
69                 this.mapper = mapper;
70         }
71
72         public Optional<URI> getRedirect(String username)
73         {
74                 KeyQueryMetadata metadata = streams.queryMetadataForKey(storeName, username, Serdes.String().serializer());
75                 HostInfo activeHost = metadata.activeHost();
76                 log.debug("Local store for {}: {}, {}:{}", username, metadata.partition(), activeHost.host(), activeHost.port());
77
78                 if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
79                 {
80                         return Optional.empty();
81                 }
82
83                 URI location = URI.create("http://" + activeHost.host() + ":" + activeHost.port() + "/" + username);
84                 log.debug("Redirecting to {}", location);
85                 return Optional.of(location);
86         }
87
88         public Optional<User> getUser(String username)
89         {
90                 return
91                                 Optional
92                                                 .ofNullable(streams.store(storeParameters).get(username))
93                                                 .map(json ->
94                                                 {
95                                                         try
96                                                         {
97                                                                 return mapper.readValue(json, User.class);
98                                                         }
99                                                         catch (JsonProcessingException e)
100                                                         {
101                                                                 throw new RuntimeException(e);
102                                                         }
103                                                 });
104         }
105
106         @PostConstruct
107         public void start()
108         {
109                 log.info("Starting Stream-Processor");
110                 streams.start();
111         }
112
113         @PreDestroy
114         public void stop()
115         {
116                 log.info("Stopping Stream-Processor");
117                 streams.close();
118         }
119 }