DLT-Konfig für `spring-consumer`, die auch mit Poison Pills umgehen kann
[demos/kafka/training] / src / main / java / de / juplo / kafka / Application.java
index 273cee5..0360f68 100644 (file)
@@ -1,14 +1,70 @@
 package de.juplo.kafka;
 
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.common.serialization.ByteArraySerializer;
+import org.apache.kafka.common.serialization.StringSerializer;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
 import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.kafka.core.DefaultKafkaProducerFactory;
+import org.springframework.kafka.core.KafkaOperations;
+import org.springframework.kafka.core.KafkaTemplate;
+import org.springframework.kafka.core.ProducerFactory;
+import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
+import org.springframework.kafka.listener.DefaultErrorHandler;
+import org.springframework.kafka.support.serializer.DelegatingByTypeSerializer;
+import org.springframework.kafka.support.serializer.JsonSerializer;
+import org.springframework.util.backoff.FixedBackOff;
+
+import java.util.Map;
 
 
 @SpringBootApplication
-@EnableConfigurationProperties(ApplicationProperties.class)
+@EnableConfigurationProperties({ KafkaProperties.class, ApplicationProperties.class })
 public class Application
 {
+  @Bean
+  public ProducerFactory<String, Object> producerFactory(
+    KafkaProperties properties)
+  {
+    Map<String, Object> map = Map.of(
+      ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServers());
+    return new DefaultKafkaProducerFactory<>(
+      map,
+      new StringSerializer(),
+      new DelegatingByTypeSerializer(
+        Map.of(
+          byte[].class, new ByteArraySerializer(),
+          MessageAddNumber.class, new JsonSerializer<>(),
+          MessageCalculateSum.class, new JsonSerializer<>())));
+  }
+
+  @Bean
+  public KafkaTemplate<String, Object> kafkaTemplate(
+    ProducerFactory<String, Object> producerFactory)
+  {
+    return new KafkaTemplate<>(producerFactory);
+  }
+
+  @Bean
+  public DeadLetterPublishingRecoverer deadLetterPublishingRecoverer(
+    KafkaOperations<?, ?> kafkaTemplate)
+  {
+    return new DeadLetterPublishingRecoverer(kafkaTemplate);
+  }
+
+  @Bean
+  public DefaultErrorHandler errorHandler(
+    DeadLetterPublishingRecoverer recoverer)
+  {
+    return new DefaultErrorHandler(
+      recoverer,
+      new FixedBackOff(0l, 0l));
+  }
+
+
   public static void main(String[] args)
   {
     SpringApplication.run(Application.class, args);