Dynamically Creating Containers

有多种技术可用于在运行时创建侦听器容器。本部分探讨其中一些技术。

There are several techniques that can be used to create listener containers at runtime. This section explores some of those techniques.

MessageListener Implementations

如果您直接实现自己的侦听器,则可以使用容器工厂简单地为该侦听器创建一个原始容器:

If you implement your own listener directly, you can simply use the container factory to create a raw container for that listener:

User Listener
  • Java

  • Kotlin

Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$java-examples/org/springframework/kafka/jdocs/dynamic/MyListener.java[]
Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$java-examples/org/springframework/kafka/jdocs/dynamic/Application.java[]
Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$kotlin-examples/org/springframework/kafka/kdocs/dynamic/Application.kt[]
Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$kotlin-examples/org/springframework/kafka/kdocs/dynamic/Application.kt[]

Prototype Beans

可以使用 @KafkaListener 注释的方法的容器可以通过将 bean 声明为 prototype 来动态创建:

Containers for methods annotated with @KafkaListener can be created dynamically by declaring the bean as prototype:

Prototype
  • Java

  • Kotlin

Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$java-examples/org/springframework/kafka/jdocs/dynamic/MyPojo.java[]
Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$java-examples/org/springframework/kafka/jdocs/dynamic/Application.java[]
Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$java-examples/org/springframework/kafka/jdocs/dynamic/Application.java[]
Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$kotlin-examples/org/springframework/kafka/kdocs/dynamic/Application.kt[]
Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$kotlin-examples/org/springframework/kafka/kdocs/dynamic/Application.kt[]
Unresolved include directive in modules/ROOT/pages/kafka/dynamic-containers.adoc - include::example$kotlin-examples/org/springframework/kafka/kdocs/dynamic/Application.kt[]

监听器必须具有唯一的 ID。从 2.8.9 版本开始,KafkaListenerEndpointRegistry 具有一个新方法 unregisterListenerContainer(String id),它允许您重复使用 id。注销容器不会注销 stop() 容器,您必须自己执行此操作。

Listeners must have unique IDs. Starting with version 2.8.9, the KafkaListenerEndpointRegistry has a new method unregisterListenerContainer(String id) to allow you to re-use an id. Unregistering a container does not stop() the container, you must do that yourself.