a1f8dbdd4388a8992d156a54c77a7fc6176339f9
[demos/microservices] / details / src / main / java / de / trion / microservices / details / DetailsService.java
1 package de.trion.microservices.details;
2
3
4 import de.trion.microservices.avro.Order;
5 import static org.springframework.http.MediaType.APPLICATION_JSON;
6 import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
7 import java.net.URI;
8 import java.util.Properties;
9 import javax.annotation.PostConstruct;
10 import javax.annotation.PreDestroy;
11 import org.apache.kafka.common.serialization.Serdes;
12 import org.apache.kafka.streams.KafkaStreams;
13 import org.apache.kafka.streams.StreamsBuilder;
14 import org.apache.kafka.streams.Topology;
15 import org.apache.kafka.streams.kstream.Materialized;
16 import org.apache.kafka.streams.state.QueryableStoreTypes;
17 import org.apache.kafka.streams.state.ReadOnlyKeyValueStore;
18 import org.apache.kafka.streams.state.StreamsMetadata;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21 import org.springframework.http.HttpStatus;
22 import org.springframework.http.MediaType;
23 import org.springframework.http.ResponseEntity;
24 import org.springframework.web.bind.annotation.GetMapping;
25 import org.springframework.web.bind.annotation.PathVariable;
26 import org.springframework.web.bind.annotation.RestController;
27
28
29 @RestController
30 public class DetailsService
31 {
32   final static Logger LOG = LoggerFactory.getLogger(DetailsService.class);
33
34   private final String topic;
35   private final String host;
36   private final int port;
37   private final KafkaStreams streams;
38
39
40   public DetailsService(ApplicationProperties config)
41   {
42     topic = config.topic;
43
44     String[] splitted = config.applicationServer.split(":");
45     host = splitted[0];
46     port = Integer.parseInt(splitted[1]);
47
48     Properties properties = new Properties();
49     properties.put("bootstrap.servers", config.bootstrapServers);
50     properties.put("application.id", "details");
51     properties.put("application.server", config.applicationServer);
52     properties.put("schema.registry.url", config.schemaRegistryUrl);
53     properties.put("default.key.serde", Serdes.String().getClass());
54     properties.put("default.value.serde", SpecificAvroSerde.class);
55
56     StreamsBuilder builder = new StreamsBuilder();
57     builder.table(topic, Materialized.as(topic));
58
59     Topology topology = builder.build();
60     streams = new KafkaStreams(topology, properties);
61     streams.setUncaughtExceptionHandler((Thread t, Throwable e) ->
62     {
63       LOG.error("Unexpected error in thread {}: {}", t, e.toString());
64       try
65       {
66         streams.close();
67       }
68       catch (Exception ex)
69       {
70         LOG.error("Could not close KafkaStreams!", ex);
71       }
72     });
73   }
74
75
76   @GetMapping(
77       path = "/orders/{id}",
78       produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
79   public ResponseEntity<?> getOrder(@PathVariable String id)
80   {
81     StreamsMetadata metadata = streams.metadataForKey(topic, id, Serdes.String().serializer());
82     LOG.debug("Local store for {}: {}:{}", id, metadata.host(), metadata.port());
83
84     if (port != metadata.port() || !host.equals(metadata.host()))
85     {
86       URI location = URI.create("http://" + metadata.host() + ":" + metadata.port() + "/" + id);
87       LOG.debug("Redirecting to {}", location);
88       return
89           ResponseEntity
90               .status(HttpStatus.TEMPORARY_REDIRECT)
91               .location(location)
92               .build();
93     }
94
95     ReadOnlyKeyValueStore<String, Order> orders;
96     orders = streams.store(topic, QueryableStoreTypes.keyValueStore());
97     Order order = orders.get(id);
98     return order == null
99         ? ResponseEntity.notFound().build()
100         : ResponseEntity.ok().contentType(APPLICATION_JSON).body(order.toString());
101   }
102
103
104   @PostConstruct
105   public void start()
106   {
107     streams.start();
108   }
109
110   @PreDestroy
111   public void stop()
112   {
113     streams.close();
114   }
115 }