1 package de.trion.kafka.outbox;
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import org.apache.kafka.clients.consumer.ConsumerRecord;
5 import org.apache.kafka.clients.consumer.ConsumerRecords;
6 import org.apache.kafka.clients.consumer.KafkaConsumer;
7 import org.apache.kafka.common.errors.WakeupException;
8 import org.apache.kafka.common.serialization.LongDeserializer;
9 import org.apache.kafka.common.serialization.StringDeserializer;
10 import org.slf4j.Logger;
11 import org.slf4j.LoggerFactory;
12 import org.springframework.boot.ApplicationArguments;
13 import org.springframework.boot.ApplicationRunner;
14 import org.springframework.stereotype.Component;
16 import javax.annotation.PreDestroy;
17 import java.time.Duration;
18 import java.util.Arrays;
19 import java.util.Properties;
23 public class OutboxConsumer implements ApplicationRunner, Runnable {
25 private final static Logger LOG = LoggerFactory.getLogger(OutboxConsumer.class);
27 private final OutboxService service;
28 private final OutboxProducer sender;
29 private final ObjectMapper mapper;
30 private final String topic;
31 private final KafkaConsumer<Long, String> consumer;
32 private final Thread thread;
34 private long internalState = 1;
37 public OutboxConsumer(
38 OutboxService service,
39 OutboxProducer sender,
41 String bootstrapServers,
45 this.service = service;
50 Properties props = new Properties();
51 props.put("bootstrap.servers", bootstrapServers);
52 props.put("group.id", consumerGroup);
53 props.put("auto.commit.interval.ms", 15000);
54 props.put("metadata.max.age.ms", 1000);
55 props.put("key.deserializer", LongDeserializer.class.getName());
56 props.put("value.deserializer", StringDeserializer.class.getName());
57 consumer = new KafkaConsumer<>(props);
59 thread = new Thread(this);
67 LOG.info("Subscribing to topic " + topic);
68 consumer.subscribe(Arrays.asList(topic));
72 ConsumerRecords<Long, String> records = consumer.poll(Duration.ofSeconds(1));
73 for (ConsumerRecord<Long, String> record : records) {
74 LOG.debug("Ignoring command {}", record.value());
78 catch (WakeupException e) {}
80 LOG.error("Unexpected exception!", e);
84 LOG.info("Closing the KafkaConsumer...");
86 consumer.close(Duration.ofSeconds(5));
87 LOG.debug("Successfully closed the KafkaConsumer");
90 LOG.warn("Exception while closing the KafkaConsumer!", e);
97 public void run(ApplicationArguments args) {
101 LOG.info("Successfully joined the consumer-thread");
103 catch (InterruptedException e) {
104 LOG.info("Main-thread was interrupted while joining the consumer-thread");
111 LOG.info("Stopping the KafkaConsumer...");