Merge der überarbeiteten Compose-Konfiguration (Branch 'headers')
[demos/kafka/training] / src / main / java / de / juplo / kafka / RestProducer.java
1 package de.juplo.kafka;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.producer.KafkaProducer;
5 import org.apache.kafka.clients.producer.ProducerRecord;
6 import org.apache.kafka.common.serialization.StringSerializer;
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.math.BigInteger;
13 import java.util.Properties;
14 import java.util.concurrent.ExecutionException;
15
16
17 @Slf4j
18 @RestController
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   public RestProducer(ApplicationProperties properties)
29   {
30     this.id = properties.getClientId();
31     this.topic = properties.getTopic();
32     this.partition = properties.getPartition();
33
34     Properties props = new Properties();
35     props.put("bootstrap.servers", properties.getBootstrapServer());
36     props.put("client.id", properties.getClientId());
37     props.put("acks", properties.getAcks());
38     props.put("batch.size", properties.getBatchSize());
39     props.put("delivery.timeout.ms", 20000); // 20 Sekunden
40     props.put("request.timeout.ms",  10000); // 10 Sekunden
41     props.put("linger.ms", properties.getLingerMs());
42     props.put("compression.type", properties.getCompressionType());
43     props.put("key.serializer", StringSerializer.class.getName());
44     props.put("value.serializer", StringSerializer.class.getName());
45
46     this.producer = new KafkaProducer<>(props);
47   }
48
49   @PostMapping(path = "{key}")
50   public DeferredResult<ProduceResult> send(
51       @PathVariable String key,
52       @RequestHeader(name = "X-id", required = false) Long correlationId,
53       @RequestBody String value)
54   {
55     DeferredResult<ProduceResult> result = new DeferredResult<>();
56
57     final long time = System.currentTimeMillis();
58
59     final ProducerRecord<String, String> record = new ProducerRecord<>(
60         topic,  // Topic
61         partition, // Partition
62         key,    // Key
63         value   // Value
64     );
65
66     // TODO: Fügen Sie die Header zu der Nachricht hinzu
67
68     producer.send(record, (metadata, e) ->
69     {
70       long now = System.currentTimeMillis();
71       if (e == null)
72       {
73         // HANDLE SUCCESS
74         produced++;
75         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
76         log.debug(
77             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
78             id,
79             record.key(),
80             record.value(),
81             metadata.partition(),
82             metadata.offset(),
83             metadata.timestamp(),
84             now - time
85         );
86       }
87       else
88       {
89         // HANDLE ERROR
90         result.setErrorResult(new ProduceFailure(e));
91         log.error(
92             "{} - ERROR key={} timestamp={} latency={}ms: {}",
93             id,
94             record.key(),
95             metadata == null ? -1 : metadata.timestamp(),
96             now - time,
97             e.toString()
98         );
99       }
100     });
101
102     long now = System.currentTimeMillis();
103     log.trace(
104         "{} - Queued message with key={} latency={}ms",
105         id,
106         record.key(),
107         now - time
108     );
109
110     return result;
111   }
112
113   @ExceptionHandler
114   @ResponseStatus(HttpStatus.BAD_REQUEST)
115   public ErrorResponse illegalStateException(IllegalStateException e)
116   {
117     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
118   }
119
120   @PreDestroy
121   public void destroy() throws ExecutionException, InterruptedException
122   {
123     log.info("{} - Destroy!", id);
124     log.info("{} - Closing the KafkaProducer", id);
125     producer.close();
126     log.info("{}: Produced {} messages in total, exiting!", id, produced);
127   }
128 }