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 java.math.BigInteger;
12
13
14 @Slf4j
15 @RequestMapping
16 @ResponseBody
17 @RequiredArgsConstructor
18 public class RestProducer
19 {
20   private final String id;
21   private final String topic;
22   private final Integer partition;
23   private final KafkaProducer<String, String> producer;
24
25   private long produced = 0;
26
27   @PostMapping(path = "{key}")
28   public DeferredResult<ProduceResult> send(
29       @PathVariable String key,
30       @RequestHeader(name = "X-id", required = false) Long correlationId,
31       @RequestBody String value)
32   {
33     DeferredResult<ProduceResult> result = new DeferredResult<>();
34
35     final long time = System.currentTimeMillis();
36
37     final ProducerRecord<String, String> record = new ProducerRecord<>(
38         topic,  // Topic
39         key,    // Key
40         value   // Value
41     );
42
43     // TODO: Nachricht versenden und Feedback geben
44     // Tipp:
45     // result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
46     // result.setErrorResult(new ProduceFailure(e));
47
48     return result;
49   }
50
51   @ExceptionHandler
52   @ResponseStatus(HttpStatus.BAD_REQUEST)
53   public ErrorResponse illegalStateException(IllegalStateException e)
54   {
55     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
56   }
57 }