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.web.bind.annotation.*;
8 import org.springframework.web.context.request.async.DeferredResult;
10 import javax.annotation.PreDestroy;
11 import java.util.Properties;
12 import java.util.concurrent.ExecutionException;
17 public class RestProducer
19 private final String id;
20 private final String topic;
21 private final Integer partition;
22 private final KafkaProducer<String, String> producer;
24 private long produced = 0;
26 public RestProducer(ApplicationProperties properties)
28 this.id = properties.getClientId();
29 this.topic = properties.getTopic();
30 this.partition = properties.getPartition();
32 Properties props = new Properties();
33 props.put("bootstrap.servers", properties.getBootstrapServer());
34 props.put("client.id", properties.getClientId());
35 props.put("acks", properties.getAcks());
36 props.put("batch.size", properties.getBatchSize());
37 props.put("delivery.timeout.ms", 20000); // 20 Sekunden
38 props.put("request.timeout.ms", 10000); // 10 Sekunden
39 props.put("linger.ms", properties.getLingerMs());
40 props.put("compression.type", properties.getCompressionType());
41 props.put("key.serializer", StringSerializer.class.getName());
42 props.put("value.serializer", StringSerializer.class.getName());
44 this.producer = new KafkaProducer<>(props);
47 @PostMapping(path = "{key}")
48 public DeferredResult<ProduceResult> send(
49 @PathVariable String key,
50 @RequestBody String value)
52 DeferredResult<ProduceResult> result = new DeferredResult<>();
54 final long time = System.currentTimeMillis();
56 final ProducerRecord<String, String> record = new ProducerRecord<>(
58 partition, // Partition
63 producer.send(record, (metadata, e) ->
65 long now = System.currentTimeMillis();
70 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
72 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
85 result.setErrorResult(new ProduceFailure(e));
87 "{} - ERROR key={} timestamp={} latency={}ms: {}",
90 metadata == null ? -1 : metadata.timestamp(),
97 long now = System.currentTimeMillis();
99 "{} - Queued #{} key={} latency={}ms",
110 public void destroy() throws ExecutionException, InterruptedException
112 log.info("{} - Destroy!", id);
113 log.info("{} - Closing the KafkaProducer", id);
115 log.info("{}: Produced {} messages in total, exiting!", id, produced);