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 KafkaProducer<String, String> producer;
24 private long produced = 0;
26 public RestProducer(ApplicationProperties properties)
28 this.id = properties.getClientId();
29 this.topic = properties.getTopic();
31 Properties props = new Properties();
32 props.put("bootstrap.servers", properties.getBootstrapServer());
33 props.put("client.id", properties.getClientId());
34 props.put("acks", properties.getAcks());
35 props.put("batch.size", properties.getBatchSize());
36 props.put("delivery.timeout.ms", 20000); // 20 Sekunden
37 props.put("request.timeout.ms", 10000); // 10 Sekunden
38 props.put("linger.ms", properties.getLingerMs());
39 props.put("compression.type", properties.getCompressionType());
40 props.put("key.serializer", StringSerializer.class.getName());
41 props.put("value.serializer", StringSerializer.class.getName());
43 this.producer = new KafkaProducer<>(props);
46 @PostMapping(path = "{key}")
47 public DeferredResult<ProduceResult> send(
48 @PathVariable String key,
49 @RequestHeader(name = "X-id", required = false) Long correlationId,
50 @RequestBody String value)
52 DeferredResult<ProduceResult> result = new DeferredResult<>();
54 final long time = System.currentTimeMillis();
56 final ProducerRecord<String, String> record = new ProducerRecord<>(
62 producer.send(record, (metadata, e) ->
64 long now = System.currentTimeMillis();
69 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
71 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
84 result.setErrorResult(new ProduceFailure(e));
86 "{} - ERROR key={} timestamp={} latency={}ms: {}",
89 metadata == null ? -1 : metadata.timestamp(),
96 long now = System.currentTimeMillis();
98 "{} - Queued #{} key={} latency={}ms",
109 @ResponseStatus(HttpStatus.BAD_REQUEST)
110 public ErrorResponse illegalStateException(IllegalStateException e)
112 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
116 public void destroy() throws ExecutionException, InterruptedException
118 log.info("{} - Destroy!", id);
119 log.info("{} - Closing the KafkaProducer", id);
121 log.info("{}: Produced {} messages in total, exiting!", id, produced);