Beispiele verwenden das Interface, um die erzeugte Instanz abzulegen
[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.Producer;
6 import org.apache.kafka.clients.producer.KafkaProducer;
7 import org.apache.kafka.clients.producer.ProducerRecord;
8 import org.springframework.http.HttpStatus;
9 import org.springframework.web.bind.annotation.*;
10 import org.springframework.web.context.request.async.DeferredResult;
11
12 import java.math.BigInteger;
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 Producer<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         partition, // Partition
41         key,    // Key
42         value   // Value
43     );
44
45     record.headers().add("source", id.getBytes());
46     if (correlationId != null)
47     {
48       record.headers().add("id", BigInteger.valueOf(correlationId).toByteArray());
49     }
50
51     producer.send(record, (metadata, e) ->
52     {
53       long now = System.currentTimeMillis();
54       if (e == null)
55       {
56         // HANDLE SUCCESS
57         produced++;
58         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
59         log.debug(
60             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
61             id,
62             record.key(),
63             record.value(),
64             metadata.partition(),
65             metadata.offset(),
66             metadata.timestamp(),
67             now - time
68         );
69       }
70       else
71       {
72         // HANDLE ERROR
73         result.setErrorResult(new ProduceFailure(e));
74         log.error(
75             "{} - ERROR key={} timestamp={} latency={}ms: {}",
76             id,
77             record.key(),
78             metadata == null ? -1 : metadata.timestamp(),
79             now - time,
80             e.toString()
81         );
82       }
83     });
84
85     long now = System.currentTimeMillis();
86     log.trace(
87         "{} - Queued message with key={} latency={}ms",
88         id,
89         record.key(),
90         now - time
91     );
92
93     return result;
94   }
95
96   @ExceptionHandler
97   @ResponseStatus(HttpStatus.BAD_REQUEST)
98   public ErrorResponse illegalStateException(IllegalStateException e)
99   {
100     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
101   }
102 }