1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.producer.RecordMetadata;
5 import org.springframework.http.HttpStatus;
6 import org.springframework.kafka.core.KafkaTemplate;
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.concurrent.ExecutionException;
16 public class RestProducer
18 private final String id;
19 private final String topic;
20 private final KafkaTemplate<String, Object> kafkaTemplate;
22 private long produced = 0;
25 ApplicationProperties properties,
26 KafkaTemplate<String, Object> kafkaTemplate)
28 this.id = properties.getClientId();
29 this.topic = properties.getTopic();
30 this.kafkaTemplate = kafkaTemplate;
33 @PostMapping(path = "{key}")
34 public DeferredResult<ProduceResult> message(
35 @PathVariable String key,
36 @RequestBody String value)
39 return send(key, new ClientMessage(key, value));
42 @PutMapping(path = "{key}")
43 public DeferredResult<ProduceResult> message(@PathVariable String key)
46 return send(key, new FooMessage(key, System.currentTimeMillis()));
49 @PostMapping(path = "/")
50 public DeferredResult<ProduceResult> greeting(
51 @RequestBody String name)
54 return send(name, new Greeting(name));
57 private DeferredResult<ProduceResult> send(String key, Object value)
59 DeferredResult<ProduceResult> result = new DeferredResult<>();
61 final long time = System.currentTimeMillis();
63 kafkaTemplate.send(topic, key, value).addCallback(
66 long now = System.currentTimeMillis();
69 RecordMetadata metadata = sendResult.getRecordMetadata();
71 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
73 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
85 long now = System.currentTimeMillis();
88 result.setErrorResult(new ProduceFailure(e));
90 "{} - ERROR key={} timestamp=-1 latency={}ms: {}",
98 long now = System.currentTimeMillis();
100 "{} - 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("{}: Produced {} messages in total, exiting!", id, produced);