Merge branch 'rest-producer' into rest-producer-vorlage
[demos/kafka/training] / src / main / java / de / juplo / kafka / RestProducer.java
1 package de.juplo.kafka;
2
3 import lombok.RequiredArgsConstructor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.producer.KafkaProducer;
6 import org.apache.kafka.clients.producer.ProducerRecord;
7 import org.springframework.http.HttpStatus;
8 import org.springframework.web.bind.annotation.*;
9 import org.springframework.web.context.request.async.DeferredResult;
10
11 import javax.annotation.PreDestroy;
12 import java.util.concurrent.ExecutionException;
13
14
15 @Slf4j
16 @RequestMapping
17 @ResponseBody
18 @RequiredArgsConstructor
19 public class RestProducer
20 {
21   private final String id;
22   private final String topic;
23   private final Integer partition;
24   private final KafkaProducer<String, String> producer;
25
26   private long produced = 0;
27
28   @PostMapping(path = "{key}")
29   public DeferredResult<ProduceResult> send(
30       @PathVariable String key,
31       @RequestHeader(name = "X-id", required = false) Long correlationId,
32       @RequestBody String value)
33   {
34     DeferredResult<ProduceResult> result = new DeferredResult<>();
35
36     final long time = System.currentTimeMillis();
37
38     final ProducerRecord<String, String> record = new ProducerRecord<>(
39         topic,  // Topic
40         key,    // Key
41         value   // Value
42     );
43
44     // TODO: Nachricht versenden und Feedback geben
45     // Tipp:
46     // result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
47     // result.setErrorResult(new ProduceFailure(e));
48
49     return result;
50   }
51
52   @ExceptionHandler
53   @ResponseStatus(HttpStatus.BAD_REQUEST)
54   public ErrorResponse illegalStateException(IllegalStateException e)
55   {
56     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
57   }
58 }