1 package de.juplo.kafka.wordcount.users;
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;
16 import javax.annotation.PostConstruct;
17 import javax.annotation.PreDestroy;
19 import java.util.Optional;
20 import java.util.Properties;
21 import java.util.concurrent.CompletableFuture;
23 import static org.apache.kafka.streams.errors.StreamsUncaughtExceptionHandler.StreamThreadExceptionResponse.SHUTDOWN_CLIENT;
27 public class UsersStreamProcessor
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;
36 public UsersStreamProcessor(
38 HostInfo applicationServer,
39 String bootstrapServer,
42 ConfigurableApplicationContext context)
44 StreamsBuilder builder = new StreamsBuilder();
45 builder.table(topic, Materialized.as(storeName));
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");
55 streams = new KafkaStreams(builder.build(), props);
56 streams.setUncaughtExceptionHandler((Throwable e) ->
58 log.error("Unexpected error!", e);
59 CompletableFuture.runAsync(() ->
61 log.info("Stopping application...");
62 SpringApplication.exit(context, () -> 1);
64 return SHUTDOWN_CLIENT;
67 hostInfo = applicationServer;
68 storeParameters = StoreQueryParameters.fromNameAndType(storeName, QueryableStoreTypes.keyValueStore());;
72 public Optional<URI> getRedirect(String username)
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());
78 if (activeHost.equals(this.hostInfo) || activeHost.equals(HostInfo.unavailable()))
80 return Optional.empty();
83 URI location = URI.create("http://" + activeHost.host() + ":" + activeHost.port() + "/" + username);
84 log.debug("Redirecting to {}", location);
85 return Optional.of(location);
88 public Optional<User> getUser(String username)
92 .ofNullable(streams.store(storeParameters).get(username))
97 return mapper.readValue(json, User.class);
99 catch (JsonProcessingException e)
101 throw new RuntimeException(e);
109 log.info("Starting Stream-Processor");
116 log.info("Stopping Stream-Processor");