简体   繁体   English

应用程序启动后的Spring Boot长期运行方法

[英]Spring boot long run method after application starts

For my Spring boot web app, after the application starts, I want to call a method of a class to keep it running until the app shutdowns. 对于我的Spring Boot Web应用程序,在应用程序启动后,我想调用一个类的方法以使其保持运行状态,直到应用程序关闭为止。 For example the logic of method is consuming a Kafka message (long polling). 例如,方法的逻辑是消耗Kafka消息(长时间轮询)。

So I end up with some following code. 因此,我得到了以下一些代码。 It works ok, but I am looking for more simplified or elegant way of doing that. 可以,但是我正在寻找更简化或更优雅的方法。

@Component
class KafkaConsumerService : ApplicationRunner {
  private lateinit var kafkaConsumer: KafkaConsumer<String, String>

  init {
    val props = Properties()
    props[ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG] = "127.0.0.1:9092"
    props[ConsumerConfig.GROUP_ID_CONFIG] = "AnotherDemoConsumer"
    props[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java.name
    props[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java.name

    kafkaConsumer = KafkaConsumer(props)
  }

  override fun run(args: ApplicationArguments?) {
    receiveFromKafka()
  }

  fun receiveFromKafka() {
    kafkaConsumer.subscribe(listOf("test-topic"))

    while (true) {
      val consumerRecords = kafkaConsumer.poll(3000)

      consumerRecords.forEach { record ->
        logger.info("Receive Kafka message having key: ${record.key()}, value: ${record.value()}, " +
            "partition: ${record.partition()}, offset: ${record.offset()}")
      }
    }
  }
}

For above code, I have to implement an ApplicationRunner interface and then override run method. 对于上面的代码,我必须实现一个ApplicationRunner接口,然后重写run方法。

Is that possible to use some other Spring boot feature without using while loop or something like scheduler?? 是否可以在不使用while循环或诸如Scheduler之类的情况下使用其他一些Spring Boot功能?

Use @EnableShceduling to turn on scheduling features of spring. 使用@EnableShceduling打开spring的调度功能。 Polling can be done in method that will be annotated by @Scheduled(3000) 轮询可以通过@Scheduled(3000)注释的方法来完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM