简体   繁体   中英

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. For example the logic of method is consuming a Kafka message (long polling).

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.

Is that possible to use some other Spring boot feature without using while loop or something like scheduler??

Use @EnableShceduling to turn on scheduling features of spring. Polling can be done in method that will be annotated by @Scheduled(3000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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