How can get MessageListenerContainer with KafkaListenerEndpointRegistry

Viewed 455

I wrote some code for healthcheck my KafkaConsumer like this:

  @Component
   class HealthCheckConsumer : ReactiveHealthIndicator {
        @Autowired
        private lateinit var kafkaListenerEndpointRegistry: KafkaListenerEndpointRegistry


        override fun health(): Mono<Health> {
         val container =
            kafkaListenerEndpointRegistry.getListenerContainer("myGroupId")
        
        println("get listener container" + container)
        
        return doHealthCheck(container)
            .onErrorResume({ ex -> Mono.just(Health.Builder().down(ex).build()) })
    }

    private fun doHealthCheck( message: MessageListenerContainer): Mono<Health> {
        if (message.isRunning)
            return Mono.just(Health.up().build())
        return Mono.error(Exception("an error was threw"))
      }
    }
  1. But when I run it, the variable container return null, even though the kafka message was received and the group Id exact with properties spring.cloud.stream.bindings.accountAsisConsumer-in-0.group.
  2. Otherwise, when I try to get all container by kafkaListenerEndpointRegistry.allListenerContainers, it returns an empty collection.

I'm wondering if I had missed some config for it, please help me with this issue. Thanks in advance.

1 Answers

The ListenerContainer must be called after a consumer got a message. In other words, you must put the line below, or call its containing method, in where body of a method is consumer. kafkaListenerEndpointRegistry.getListenerContainer("myGroupId")

Related