如果属性中的kafka主题名称在kafka中不存在,如何中断启动spring-boot应用程序?

时间:2019-04-02 08:34:28

标签: java spring-boot spring-kafka

我尝试检查有关启动spring-boot应用程序的Kafka主题。我想引发异常并中断启动。这是我的配置:

@Slf4j
@Configuration
public class KafkaTopicConfig implements ApplicationRunner {

    private final KafkaAdmin kafkaAdmin;
    private final TopicProperties topicProperties;

    public KafkaTopicConfig(KafkaAdmin kafkaAdmin, TopicProperties topicProperties) {
        this.kafkaAdmin = kafkaAdmin;
        this.topicProperties = topicProperties;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        AdminClient admin = AdminClient.create(kafkaAdmin.getConfig());

        ListTopicsResult listTopicsResult = admin.listTopics();
        listTopicsResult.names().whenComplete((existTopics, throwable) -> {
            log.info("TOPICS LOAD: {}", existTopics.size());
            topicProperties.getTopics().forEach((s, topic) -> {
                if (!existTopics.contains(topic))
                    throw new IllegalStateException("Topic with name: " + topic + " not found in kafka.");
            });
        });
    }
}

但是在抛出throw new IllegalStateException("Topic with name: " + topic + " not found in kafka.");之后,此异常将被忽略,应用程序可以继续工作。

1 个答案:

答案 0 :(得分:0)

ApplicationRunner实现SmartLifecycle而不是autoStartup=true,并将您的逻辑放入start()