Für das Versenden wird das `KafkaTemplate` von Spring verwendet
[demos/kafka/training] / src / main / java / de / juplo / kafka / RestProducer.java
index 7a5b324..56f3382 100644 (file)
 package de.juplo.kafka;
 
 import lombok.extern.slf4j.Slf4j;
-import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.ProducerRecord;
-import org.apache.kafka.common.serialization.StringSerializer;
+import org.apache.kafka.clients.producer.RecordMetadata;
+import org.springframework.http.HttpStatus;
+import org.springframework.kafka.core.KafkaTemplate;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.context.request.async.DeferredResult;
 
 import javax.annotation.PreDestroy;
-import java.util.Properties;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
 
 
 @Slf4j
-public class EndlessProducer implements Runnable
+@RestController
+public class RestProducer
 {
-  private final ExecutorService executor;
   private final String id;
   private final String topic;
-  private final int throttleMs;
-  private final KafkaProducer<String, String> producer;
+  private final KafkaTemplate<String, Object> kafkaTemplate;
 
-  private boolean running = false;
-  private long i = 0;
   private long produced = 0;
 
-  public EndlessProducer(
-      ExecutorService executor,
-      String bootstrapServer,
-      String clientId,
-      String topic,
-      String acks,
-      int throttleMs)
+  public RestProducer(
+      ApplicationProperties properties,
+      KafkaTemplate<String, Object> kafkaTemplate)
   {
-    this.executor = executor;
-    this.id = clientId;
-    this.topic = topic;
-    this.throttleMs = throttleMs;
-
-    Properties props = new Properties();
-    props.put("bootstrap.servers", bootstrapServer);
-    props.put("client.id", clientId);
-    props.put("acks", acks);
-    props.put("key.serializer", StringSerializer.class.getName());
-    props.put("value.serializer", StringSerializer.class.getName());
-
-    this.producer = new KafkaProducer<>(props);
+    this.id = properties.getClientId();
+    this.topic = properties.getTopic();
+    this.kafkaTemplate = kafkaTemplate;
   }
 
-  @Override
-  public void run()
+  @PostMapping(path = "{key}")
+  public DeferredResult<ProduceResult> message(
+      @PathVariable String key,
+      @RequestBody String value)
   {
-    try
-    {
-      for (; running; i++)
-      {
-        send(Long.toString(i%10), Long.toString(i));
-
-        if (throttleMs > 0)
-        {
-          try
-          {
-            Thread.sleep(throttleMs);
-          }
-          catch (InterruptedException e)
-          {
-            log.warn("{} - Interrupted while throttling!", e);
-          }
-        }
-      }
-
-      log.info("{} - Done", id);
-    }
-    catch (Exception e)
-    {
-      log.error("{} - Unexpected Exception:", id, e);
-    }
-    finally
-    {
-      synchronized (this)
-      {
-        running = false;
-        log.info("{} - Stopped - produced {} messages so far", id, produced);
-      }
-    }
+    key = key.trim();
+    final ProducerRecord<String, Object> record = new ProducerRecord<>(
+        topic,  // Topic
+        key,    // Key
+        new ClientMessage(key, value) // Value
+    );
+
+    return send(record);
   }
 
-  void send(String key, String value)
+  @PutMapping(path = "{key}")
+  public DeferredResult<ProduceResult> message(@PathVariable String key)
   {
-    final long time = System.currentTimeMillis();
-
-    final ProducerRecord<String, String> record = new ProducerRecord<>(
+    key = key.trim();
+    final ProducerRecord<String, Object> record = new ProducerRecord<>(
         topic,  // Topic
         key,    // Key
-        value   // Value
+        new FooMessage(key, System.currentTimeMillis()) // Value
+    );
+
+    return send(record);
+  }
+
+  @PostMapping(path = "/")
+  public DeferredResult<ProduceResult> greeting(
+      @RequestBody String name)
+  {
+    name = name.trim();
+    final ProducerRecord<String, Object> record = new ProducerRecord<>(
+        topic,  // Topic
+        name,    // Key
+        new Greeting(name) // Value
     );
 
-    producer.send(record, (metadata, e) ->
-    {
-      long now = System.currentTimeMillis();
-      if (e == null)
+    return send(record);
+  }
+
+  private DeferredResult<ProduceResult> send(ProducerRecord<String, Object> record)
+  {
+    DeferredResult<ProduceResult> result = new DeferredResult<>();
+
+    final long time = System.currentTimeMillis();
+
+    kafkaTemplate.send(record).addCallback(
+      (sendResult) ->
       {
+        long now = System.currentTimeMillis();
+
         // HANDLE SUCCESS
+        RecordMetadata metadata = sendResult.getRecordMetadata();
         produced++;
+        result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
         log.debug(
             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
             id,
@@ -112,67 +98,44 @@ public class EndlessProducer implements Runnable
             metadata.timestamp(),
             now - time
         );
-      }
-      else
+      },
+      (e) ->
       {
+        long now = System.currentTimeMillis();
+
         // HANDLE ERROR
+        result.setErrorResult(new ProduceFailure(e));
         log.error(
-            "{} - ERROR key={} timestamp={} latency={}ms: {}",
+            "{} - ERROR key={} timestamp=-1 latency={}ms: {}",
             id,
             record.key(),
-            metadata == null ? -1 : metadata.timestamp(),
             now - time,
             e.toString()
         );
-      }
-    });
+      });
 
     long now = System.currentTimeMillis();
     log.trace(
-        "{} - Queued #{} key={} latency={}ms",
+        "{} - Queued key={} latency={}ms",
         id,
-        value,
         record.key(),
         now - time
     );
-  }
 
-  public synchronized void start()
-  {
-    if (running)
-      throw new IllegalStateException("Producer instance " + id + " is already running!");
-
-    log.info("{} - Starting - produced {} messages before", id, produced);
-    running = true;
-    executor.submit(this);
+    return result;
   }
 
-  public synchronized void stop() throws ExecutionException, InterruptedException
+  @ExceptionHandler
+  @ResponseStatus(HttpStatus.BAD_REQUEST)
+  public ErrorResponse illegalStateException(IllegalStateException e)
   {
-    if (!running)
-      throw new IllegalStateException("Producer instance " + id + " is not running!");
-
-    log.info("{} - Stopping...", id);
-    running = false;
+    return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
   }
 
   @PreDestroy
   public void destroy() throws ExecutionException, InterruptedException
   {
     log.info("{} - Destroy!", id);
-    try
-    {
-      stop();
-    }
-    catch (IllegalStateException e)
-    {
-      log.info("{} - Was already stopped", id);
-    }
-    finally
-    {
-      log.info("{} - Closing the KafkaProducer", id);
-      producer.close();
-      log.info("{}: Produced {} messages in total, exiting!", id, produced);
-    }
+    log.info("{}: Produced {} messages in total, exiting!", id, produced);
   }
 }