@KafkaListener as a Meta Annotation

从 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) {
    ...
}