public class Application implements ApplicationRunner
{
@Autowired
- Consumer<?, ?> consumer;
+ Consumer<?, ?> kafkaConsumer;
@Autowired
SimpleConsumer simpleConsumer;
public void run(ApplicationArguments args) throws Exception
{
log.info("Starting SimpleConsumer");
- simpleConsumer.start();
+ simpleConsumer.run();
}
@PreDestroy
public void stop() throws ExecutionException, InterruptedException
{
log.info("Signaling SimpleConsumer to quit its work");
- consumer.wakeup();
+ kafkaConsumer.wakeup();
+
+ while (simpleConsumer.isRunning())
+ {
+ log.info("Waiting for SimpleConsumer to finish its work");
+ try
+ {
+ Thread.sleep(1000);
+ }
+ catch (InterruptedException e) {}
+ }
+ log.info("SimpleConsumer finished its work");
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import org.springframework.core.task.TaskExecutor;
import org.springframework.kafka.core.ConsumerFactory;
{
@Bean
public SimpleConsumer endlessConsumer(
- TaskExecutor taskExecutor,
Consumer<String, String> kafkaConsumer,
KafkaProperties kafkaProperties,
ApplicationProperties applicationProperties)
{
return
new SimpleConsumer(
- taskExecutor,
kafkaProperties.getClientId(),
applicationProperties.getTopic(),
kafkaConsumer);
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.common.errors.WakeupException;
-import org.springframework.core.task.TaskExecutor;
+import org.springframework.scheduling.annotation.Async;
import java.time.Duration;
import java.util.Arrays;
@Slf4j
@RequiredArgsConstructor
-public class SimpleConsumer implements Runnable
+public class SimpleConsumer
{
- private final TaskExecutor taskExecutor;
private final String id;
private final String topic;
private final Consumer<String, String> consumer;
+ private volatile boolean running = false;
private long consumed = 0;
- public void start()
- {
- taskExecutor.execute(this);
- }
-
- @Override
+ @Async
public void run()
{
try
{
log.info("{} - Subscribing to topic test", id);
consumer.subscribe(Arrays.asList(topic));
+ running = true;
while (true)
{
}
finally
{
+ running = false;
log.info("{} - Closing the KafkaConsumer", id);
consumer.close();
log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
}
}
+
+ public boolean isRunning()
+ {
+ return running;
+ }
}