Dynamically Creating Containers
有多种技术可用于在运行时创建侦听器容器。本部分探讨其中一些技术。
MessageListener Implementations
如果您直接实现自己的侦听器,则可以使用容器工厂简单地为该侦听器创建一个原始容器:
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 来动态创建:
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()
容器,您必须自己执行此操作。