此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 spring-cloud-stream 4.1.4spring-doc.cadn.net.cn

Kafka Binder 侦听器容器定制器

Spring Cloud Stream 通过使用定制器为消息侦听器容器提供了强大的定制选项。 本节介绍可用于 Kafka 的定制器接口:ListenerContainerCustomizer,其特定于 Kafka 的扩展KafkaListenerContainerCustomizer和专用的ListenerContainerWithDlqAndRetryCustomizer.spring-doc.cadn.net.cn

ListenerContainerCustomizer

ListenerContainerCustomizer是 Spring Cloud Stream 中的一个通用接口,允许自定义消息侦听器容器。spring-doc.cadn.net.cn

目的

当您需要修改侦听器容器的行为时,请使用此定制器。spring-doc.cadn.net.cn

用法

要使用ListenerContainerCustomizer,请在您的配置中创建一个实现此接口的 Bean:spring-doc.cadn.net.cn

@Bean
public ListenerContainerCustomizer<AbstractMessageListenerContainer<?, ?>> genericCustomizer() {
    return (container, destinationName, group) -> {
        // Customize the container here
    };
}

ListenerContainerCustomizerinterface 定义以下方法:spring-doc.cadn.net.cn

void configure(C container, String destinationName, String group);

KafkaListenerContainerCustomizer

KafkaListenerContainerCustomizer接口扩展ListenerContainerCustomizer修改侦听器容器的行为,并提供对特定于绑定的扩展 Kafka 使用者属性的访问。spring-doc.cadn.net.cn

目的

当您需要在自定义侦听器容器时访问特定于绑定的扩展 Kafka 使用者属性时,请使用此定制器。spring-doc.cadn.net.cn

用法

要使用KafkaListenerContainerCustomizer,请在您的配置中创建一个实现此接口的 Bean:spring-doc.cadn.net.cn

@Bean
public KafkaListenerContainerCustomizer<AbstractMessageListenerContainer<?, ?>> kafkaCustomizer() {
    return (container, destinationName, group, properties) -> {
        // Customize the Kafka container here
    };
}

KafkaListenerContainerCustomizerinterface 添加了以下方法:spring-doc.cadn.net.cn

default void configureKafkaListenerContainer(
    C container,
    String destinationName,
    String group,
    ExtendedConsumerProperties<KafkaConsumerProperties> extendedConsumerProperties) {
        configure(container, destinationName, group);
}

此方法扩展了 baseconfigure方法中附加参数:spring-doc.cadn.net.cn

  • extendedConsumerProperties:扩展的使用者属性,包括 Kafka 特定的属性。spring-doc.cadn.net.cn

ListenerContainerWithDlqAndRetryCustomizer

ListenerContainerWithDlqAndRetryCustomizer界面为涉及死信队列 (DLQ) 和重试机制的场景提供了其他自定义选项。spring-doc.cadn.net.cn

目的

当您需要微调 DLQ 行为或为 Kafka 使用者实施自定义重试逻辑时,请使用此定制器。spring-doc.cadn.net.cn

用法

要使用ListenerContainerWithDlqAndRetryCustomizer,请在您的配置中创建一个实现此接口的 Bean:spring-doc.cadn.net.cn

@Bean
public ListenerContainerWithDlqAndRetryCustomizer dlqCustomizer() {
    return (container, destinationName, group, dlqDestinationResolver, backOff, properties) -> {
        // Access the container here with access to the extended consumer binding properties.
    };
}

ListenerContainerWithDlqAndRetryCustomizerinterface 定义以下方法:spring-doc.cadn.net.cn

void configure(
    AbstractMessageListenerContainer<?, ?> container,
    String destinationName,
    String group,
    BiFunction<ConsumerRecord<?, ?>, Exception, TopicPartition> dlqDestinationResolver,
    BackOff backOff,
    ExtendedConsumerProperties<KafkaConsumerProperties> extendedConsumerProperties
);

总结

这种分层方法允许在 Spring Cloud Stream 应用程序中灵活、具体地自定义 Kafka 侦听器容器。spring-doc.cadn.net.cn