Tags für die Übung ergänzt
[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         partition, // Partition
40         key,    // Key
41         value   // Value
42     );
43
44     record.headers().add("source", id.getBytes());
45     if (correlationId != null)
46     {
47       record.headers().add("id", BigInteger.valueOf(correlationId).toByteArray());
48     }
49
50     producer.send(record, (metadata, e) ->
51     {
52       long now = System.currentTimeMillis();
53       if (e == null)
54       {
55         // HANDLE SUCCESS
56         produced++;
57         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
58         log.debug(
59             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
60             id,
61             record.key(),
62             record.value(),
63             metadata.partition(),
64             metadata.offset(),
65             metadata.timestamp(),
66             now - time
67         );
68       }
69       else
70       {
71         // HANDLE ERROR
72         result.setErrorResult(new ProduceFailure(e));
73         log.error(
74             "{} - ERROR key={} timestamp={} latency={}ms: {}",
75             id,
76             record.key(),
77             metadata == null ? -1 : metadata.timestamp(),
78             now - time,
79             e.toString()
80         );
81       }
82     });
83
84     long now = System.currentTimeMillis();
85     log.trace(
86         "{} - Queued message with key={} latency={}ms",
87         id,
88         record.key(),
89         now - time
90     );
91
92     return result;
93   }
94
95   @ExceptionHandler
96   @ResponseStatus(HttpStatus.BAD_REQUEST)
97   public ErrorResponse illegalStateException(IllegalStateException e)
98   {
99     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
100   }
101 }