Parameter `partition` wiederbelebt
[demos/kafka/training] / src / main / java / de / juplo / kafka / RestGateway.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
12 @Slf4j
13 @RequestMapping
14 @ResponseBody
15 @RequiredArgsConstructor
16 public class RestGateway
17 {
18   private final String id;
19   private final String topic;
20   private final Integer partition;
21   private final KafkaProducer<String, Integer> producer;
22
23   private long produced = 0;
24
25   @PostMapping(path = "{key}")
26   public DeferredResult<ProduceResult> send(
27       @PathVariable String key,
28       @RequestHeader(name = "X-id", required = false) Long correlationId,
29       @RequestBody Integer value)
30   {
31     DeferredResult<ProduceResult> result = new DeferredResult<>();
32
33     final long time = System.currentTimeMillis();
34
35     final ProducerRecord<String, Integer> record = new ProducerRecord<>(
36         topic,  // Topic
37         partition, // Partition - Uses default-algorithm, if null
38         key,    // Key
39         value   // Value
40     );
41
42     producer.send(record, (metadata, e) ->
43     {
44       long now = System.currentTimeMillis();
45       if (e == null)
46       {
47         // HANDLE SUCCESS
48         produced++;
49         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
50         log.debug(
51             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
52             id,
53             record.key(),
54             record.value(),
55             metadata.partition(),
56             metadata.offset(),
57             metadata.timestamp(),
58             now - time
59         );
60       }
61       else
62       {
63         // HANDLE ERROR
64         result.setErrorResult(new ProduceFailure(e));
65         log.error(
66             "{} - ERROR key={} timestamp={} latency={}ms: {}",
67             id,
68             record.key(),
69             metadata == null ? -1 : metadata.timestamp(),
70             now - time,
71             e.toString()
72         );
73       }
74     });
75
76     long now = System.currentTimeMillis();
77     log.trace(
78         "{} - Queued message with key={} latency={}ms",
79         id,
80         record.key(),
81         now - time
82     );
83
84     return result;
85   }
86
87   @ExceptionHandler
88   @ResponseStatus(HttpStatus.BAD_REQUEST)
89   public ErrorResponse illegalStateException(IllegalStateException e)
90   {
91     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
92   }
93 }