1 package de.juplo.kafka;
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;
11 import javax.annotation.PreDestroy;
12 import java.util.Properties;
13 import java.util.concurrent.ExecutionException;
18 public class RestProducer
20 private final String id;
21 private final String topic;
22 private final Integer partition;
23 private final KafkaProducer<String, String> producer;
25 private long produced = 0;
27 public RestProducer(ApplicationProperties properties)
29 this.id = properties.getClientId();
30 this.topic = properties.getTopic();
31 this.partition = properties.getPartition();
33 Properties props = new Properties();
34 props.put("bootstrap.servers", properties.getBootstrapServer());
35 props.put("client.id", properties.getClientId());
36 props.put("acks", properties.getAcks());
37 props.put("batch.size", properties.getBatchSize());
38 props.put("delivery.timeout.ms", 20000); // 20 Sekunden
39 props.put("request.timeout.ms", 10000); // 10 Sekunden
40 props.put("linger.ms", properties.getLingerMs());
41 props.put("compression.type", properties.getCompressionType());
42 props.put("key.serializer", StringSerializer.class.getName());
43 props.put("value.serializer", StringSerializer.class.getName());
45 this.producer = new KafkaProducer<>(props);
48 @PostMapping(path = "{key}")
49 public DeferredResult<ProduceResult> send(
50 @PathVariable String key,
51 @RequestHeader(name = "X-id", required = false) Long correlationId,
52 @RequestBody String value)
54 DeferredResult<ProduceResult> result = new DeferredResult<>();
56 final long time = System.currentTimeMillis();
58 final ProducerRecord<String, String> record = new ProducerRecord<>(
60 partition, // Partition
65 producer.send(record, (metadata, e) ->
67 long now = System.currentTimeMillis();
72 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
74 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
87 result.setErrorResult(new ProduceFailure(e));
89 "{} - ERROR key={} timestamp={} latency={}ms: {}",
92 metadata == null ? -1 : metadata.timestamp(),
99 long now = System.currentTimeMillis();
101 "{} - Queued message with key={} latency={}ms",
111 @ResponseStatus(HttpStatus.BAD_REQUEST)
112 public ErrorResponse illegalStateException(IllegalStateException e)
114 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
118 public void destroy() throws ExecutionException, InterruptedException
120 log.info("{} - Destroy!", id);
121 log.info("{} - Closing the KafkaProducer", id);
123 log.info("{}: Produced {} messages in total, exiting!", id, produced);