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.http.MediaType;
9 import org.springframework.web.bind.annotation.*;
10 import org.springframework.web.context.request.async.DeferredResult;
12 import javax.annotation.PreDestroy;
13 import java.util.Properties;
14 import java.util.concurrent.ExecutionException;
15 import java.util.concurrent.ExecutorService;
20 public class RestProducer
22 private final String id;
23 private final String topic;
24 private final KafkaProducer<String, String> producer;
26 private long produced = 0;
28 public RestProducer(ApplicationProperties properties)
30 this.id = properties.getClientId();
31 this.topic = properties.getTopic();
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 @RequestBody String value)
53 DeferredResult<ProduceResult> result = new DeferredResult<>();
55 final long time = System.currentTimeMillis();
57 final ProducerRecord<String, String> record = new ProducerRecord<>(
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 @ResponseStatus(HttpStatus.BAD_REQUEST)
111 public ErrorResponse illegalStateException(IllegalStateException e)
113 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
117 public void destroy() throws ExecutionException, InterruptedException
119 log.info("{} - Destroy!", id);
120 log.info("{} - Closing the KafkaProducer", id);
122 log.info("{}: Produced {} messages in total, exiting!", id, produced);