Merge der Upgrades für Confluent/Spring-Boot (Branch 'customized')
[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     record.headers().add("source", id.getBytes());
67     if (correlationId != null)
68     {
69       record.headers().add("id", BigInteger.valueOf(correlationId).toByteArray());
70     }
71
72     producer.send(record, (metadata, e) ->
73     {
74       long now = System.currentTimeMillis();
75       if (e == null)
76       {
77         // HANDLE SUCCESS
78         produced++;
79         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
80         log.debug(
81             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
82             id,
83             record.key(),
84             record.value(),
85             metadata.partition(),
86             metadata.offset(),
87             metadata.timestamp(),
88             now - time
89         );
90       }
91       else
92       {
93         // HANDLE ERROR
94         result.setErrorResult(new ProduceFailure(e));
95         log.error(
96             "{} - ERROR key={} timestamp={} latency={}ms: {}",
97             id,
98             record.key(),
99             metadata == null ? -1 : metadata.timestamp(),
100             now - time,
101             e.toString()
102         );
103       }
104     });
105
106     long now = System.currentTimeMillis();
107     log.trace(
108         "{} - Queued #{} key={} latency={}ms",
109         id,
110         value,
111         record.key(),
112         now - time
113     );
114
115     return result;
116   }
117
118   @ExceptionHandler
119   @ResponseStatus(HttpStatus.BAD_REQUEST)
120   public ErrorResponse illegalStateException(IllegalStateException e)
121   {
122     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
123   }
124
125   @PreDestroy
126   public void destroy() throws ExecutionException, InterruptedException
127   {
128     log.info("{} - Destroy!", id);
129     log.info("{} - Closing the KafkaProducer", id);
130     producer.close();
131     log.info("{}: Produced {} messages in total, exiting!", id, produced);
132   }
133 }