1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.producer.ProducerRecord;
5 import org.apache.kafka.clients.producer.RecordMetadata;
6 import org.springframework.http.HttpStatus;
7 import org.springframework.kafka.core.KafkaTemplate;
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.concurrent.ExecutionException;
17 public class RestProducer
19 private final String id;
20 private final String topic;
21 private final KafkaTemplate<String, Object> kafkaTemplate;
23 private long produced = 0;
26 ApplicationProperties properties,
27 KafkaTemplate<String, Object> kafkaTemplate)
29 this.id = properties.getClientId();
30 this.topic = properties.getTopic();
31 this.kafkaTemplate = kafkaTemplate;
34 @PostMapping(path = "{key}")
35 public DeferredResult<ProduceResult> message(
36 @PathVariable String key,
37 @RequestBody String value)
40 final ProducerRecord<String, Object> record = new ProducerRecord<>(
43 new ClientMessage(key, value) // Value
49 @PutMapping(path = "{key}")
50 public DeferredResult<ProduceResult> message(@PathVariable String key)
53 final ProducerRecord<String, Object> record = new ProducerRecord<>(
56 new FooMessage(key, System.currentTimeMillis()) // Value
62 @PostMapping(path = "/")
63 public DeferredResult<ProduceResult> greeting(
64 @RequestBody String name)
67 final ProducerRecord<String, Object> record = new ProducerRecord<>(
70 new Greeting(name) // Value
76 private DeferredResult<ProduceResult> send(ProducerRecord<String, Object> record)
78 DeferredResult<ProduceResult> result = new DeferredResult<>();
80 final long time = System.currentTimeMillis();
82 kafkaTemplate.send(record).addCallback(
85 long now = System.currentTimeMillis();
88 RecordMetadata metadata = sendResult.getRecordMetadata();
90 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
92 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
104 long now = System.currentTimeMillis();
107 result.setErrorResult(new ProduceFailure(e));
109 "{} - ERROR key={} timestamp=-1 latency={}ms: {}",
117 long now = System.currentTimeMillis();
119 "{} - Queued key={} latency={}ms",
129 @ResponseStatus(HttpStatus.BAD_REQUEST)
130 public ErrorResponse illegalStateException(IllegalStateException e)
132 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
136 public void destroy() throws ExecutionException, InterruptedException
138 log.info("{} - Destroy!", id);
139 log.info("{}: Produced {} messages in total, exiting!", id, produced);