Search code examples
javaspring-bootapache-kafkakafka-consumer-apispring-kafka

Randomly generated group id for Kafka Consumer


We have an application that uses spring kafka to read messages. It is necessary that each instance of the application has a unique groupId, as well as reset it and get a new one on restart. The GroupId is randomly generated via ${random.uuid}.

Is the solution to generate randomly id really correct?


Solution

  • Yes, generating through ${random.uuid} is correct.

    spring.kafka.consumer.group-id=${random.uuid}
    

    There is also another choice if you want more control over the way the group id is generated. Use the @KafkaListener annotation with a Spring expression. From the Spring Kafka reference:

    You can configure most attributes on the annotation with SpEL by using #{…​} or property placeholders (${…​}). See the Javadoc for more information.

    @KafkaListener(topics = "hi", groupId = "#{T(java.util.UUID).randomUUID().toString()}")