@KafkaListener 作為元註解

從 2.2 版本開始,您現在可以將 @KafkaListener 用作元註解。以下示例展示瞭如何實現這一點

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@KafkaListener
public @interface MyThreeConsumersListener {

    @AliasFor(annotation = KafkaListener.class, attribute = "id")
    String id();

    @AliasFor(annotation = KafkaListener.class, attribute = "topics")
    String[] topics();

    @AliasFor(annotation = KafkaListener.class, attribute = "concurrency")
    String concurrency() default "3";

}

您必須別名化 topicstopicPatterntopicPartitions 中的至少一個(通常還需要別名 idgroupId,除非您已在消費者工廠配置中指定了 group.id)。以下示例展示瞭如何實現這一點

@MyThreeConsumersListener(id = "my.group", topics = "my.topic")
public void listen1(String in) {
    ...
}