Apache Kafka 支持

概述

Spring Integration 对 Apache Kafka 的支持基于 Spring for Apache Kafka 项目

你需要将此依赖项添加到你的项目中:

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-kafka</artifactId>
    <version>{project-version}</version>
</dependency>
compile "org.springframework.integration:spring-integration-kafka:{project-version}"

它提供了以下组件:

出站通道适配器

出站通道适配器用于将消息从 Spring Integration 通道发布到 Apache Kafka 主题。 该通道在应用程序上下文中定义,然后连接到向 Apache Kafka 发送消息的应用程序。 发送应用程序可以通过使用 Spring Integration 消息发布到 Apache Kafka,这些消息由出站通道适配器在内部转换为 Kafka 记录,如下所示:

  • Spring Integration 消息的有效负载用于填充 Kafka 记录的有效负载。

  • 默认情况下,Spring Integration 消息的 kafka_messageKey 头用于填充 Kafka 记录的键。

你可以分别通过 kafka_topickafka_partitionId 头来自定义发布消息的目标主题和分区。

此外,<int-kafka:outbound-channel-adapter> 提供了通过对出站消息应用 SpEL 表达式来提取键、目标主题和目标分区的能力。 为此,它支持三对互斥的属性:

  • topictopic-expression

  • message-keymessage-key-expression

  • partition-idpartition-id-expression

这些属性允许你将 topicmessage-keypartition-id 分别指定为适配器上的静态值,或者在运行时根据请求消息动态评估它们的值。

KafkaHeaders 接口(由 spring-kafka 提供)包含用于与头交互的常量。 messageKeytopic 默认头现在需要 kafka_ 前缀。 从使用旧头部的早期版本迁移时,你需要在 <int-kafka:outbound-channel-adapter> 上指定 message-key-expression="headers['messageKey']"topic-expression="headers['topic']"。 或者,你可以使用 <header-enricher>MessageBuilder 将上游的头部更改为 KafkaHeaders 中的新头部。 如果使用常量值,你还可以通过 topicmessage-key 在适配器上配置它们。

NOTE : 如果适配器配置了主题或消息键(无论是常量还是表达式),则使用这些配置,并忽略相应的头部。 如果你希望头部覆盖配置,则需要在表达式中配置它,例如:

topic-expression="headers['topic'] != null ? headers['topic'] : 'myTopic'"

适配器需要一个 KafkaTemplate,而 KafkaTemplate 又需要一个配置合适的 KafkaProducerFactory

如果提供了 send-failure-channel (sendFailureChannel) 并且收到 send() 失败(同步或异步),则 ErrorMessage 将发送到该通道。 有效负载是一个 KafkaSendFailureException,包含 failedMessagerecordProducerRecord)和 cause 属性。 你可以通过设置 error-message-strategy 属性来覆盖 DefaultErrorMessageStrategy

如果提供了 send-success-channel (sendSuccessChannel),则在成功发送后会发送一个有效负载类型为 org.apache.kafka.clients.producer.RecordMetadata 的消息。

如果你的应用程序使用事务,并且同一个通道适配器用于发布消息,其中事务由监听器容器启动,以及在没有现有事务的情况下发布消息,则你必须在 KafkaTemplate 上配置 transactionIdPrefix,以覆盖容器或事务管理器使用的前缀。 容器启动的事务(生产者工厂或事务管理器属性)使用的前缀在所有应用程序实例上必须相同。 仅用于生产者事务的前缀在所有应用程序实例上必须是唯一的。

你可以配置一个 flushExpression,它必须解析为布尔值。 如果你正在使用 linger.msbatch.size Kafka 生产者属性,在发送多条消息后进行刷新可能会很有用;表达式应在最后一条消息上评估为 Boolean.TRUE,并且不完整的批次将立即发送。 默认情况下,该表达式会在 KafkaIntegrationHeaders.FLUSH 头部 (kafka_flush) 中查找 Boolean 值。 如果值为 true,则会发生刷新;如果为 false 或头部不存在,则不会发生刷新。

KafkaProducerMessageHandler.sendTimeoutExpression 的默认值已从 10 秒更改为 delivery.timeout.ms Kafka 生产者属性 + 5000,以便在超时后将实际的 Kafka 错误传播到应用程序,而不是由该框架生成的超时。 此更改是为了保持一致性,因为你可能会遇到意外行为(Spring 可能会使发送超时,但实际上最终会成功)。 重要提示:该超时默认为 120 秒,因此你可能希望缩短它以获得更及时的失败。

配置

以下示例显示了如何为 Apache Kafka 配置出站通道适配器:

  • Java DSL

  • Java

  • XML

@Bean
public ProducerFactory<Integer, String> producerFactory() {
    return new DefaultKafkaProducerFactory<>(KafkaTestUtils.producerProps(embeddedKafka));
}

@Bean
public IntegrationFlow sendToKafkaFlow() {
    return f -> f
            .splitWith(s -> s.<String>function(p -> Stream.generate(() -> p).limit(101).iterator()))
            .publishSubscribeChannel(c -> c
                    .subscribe(sf -> sf.handle(
                            kafkaMessageHandler(producerFactory(), TEST_TOPIC1)
                                    .timestampExpression("T(Long).valueOf('1487694048633')"),
                            e -> e.id("kafkaProducer1")))
                    .subscribe(sf -> sf.handle(
                            kafkaMessageHandler(producerFactory(), TEST_TOPIC2)
                                   .timestamp(m -> 1487694048644L),
                            e -> e.id("kafkaProducer2")))
            );
}

@Bean
public DefaultKafkaHeaderMapper mapper() {
    return new DefaultKafkaHeaderMapper();
}

private KafkaProducerMessageHandlerSpec<Integer, String, ?> kafkaMessageHandler(
        ProducerFactory<Integer, String> producerFactory, String topic) {
    return Kafka
            .outboundChannelAdapter(producerFactory)
            .messageKey(m -> m
                    .getHeaders()
                    .get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER))
            .headerMapper(mapper())
            .partitionId(m -> 10)
            .topicExpression("headers[kafka_topic] ?: '" + topic + "'")
            .configureKafkaTemplate(t -> t.id("kafkaTemplate:" + topic));
}
@Bean
@ServiceActivator(inputChannel = "toKafka")
public MessageHandler handler() throws Exception {
    KafkaProducerMessageHandler<String, String> handler =
            new KafkaProducerMessageHandler<>(kafkaTemplate());
    handler.setTopicExpression(new LiteralExpression("someTopic"));
    handler.setMessageKeyExpression(new LiteralExpression("someKey"));
    handler.setSuccessChannel(successes());
    handler.setFailureChannel(failures());
    return handler;
}

@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
    return new KafkaTemplate<>(producerFactory());
}

@Bean
public ProducerFactory<String, String> producerFactory() {
    Map<String, Object> props = new HashMap<>();
    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, this.brokerAddress);
    // set more properties
    return new DefaultKafkaProducerFactory<>(props);
}
<int-kafka:outbound-channel-adapter id="kafkaOutboundChannelAdapter"
                                    kafka-template="template"
                                    auto-startup="false"
                                    channel="inputToKafka"
                                    topic="foo"
                                    sync="false"
                                    message-key-expression="'bar'"
                                    send-failure-channel="failures"
                                    send-success-channel="successes"
                                    error-message-strategy="ems"
                                    partition-id-expression="2">
</int-kafka:outbound-channel-adapter>

<bean id="template" class="org.springframework.kafka.core.KafkaTemplate">
    <constructor-arg>
        <bean class="org.springframework.kafka.core.DefaultKafkaProducerFactory">
            <constructor-arg>
                <map>
                    <entry key="bootstrap.servers" value="localhost:9092" />
                    ... <!-- more producer properties -->
                </map>
            </constructor-arg>
        </bean>
    </constructor-arg>
</bean>

消息驱动通道适配器

KafkaMessageDrivenChannelAdapter (<int-kafka:message-driven-channel-adapter>) 使用 spring-kafkaKafkaMessageListenerContainerConcurrentListenerContainer

此外,mode 属性也可用。 它可以接受 recordbatch 值(默认值:record)。 对于 record 模式,每个消息有效负载都从单个 ConsumerRecord 转换而来。 对于 batch 模式,有效负载是一个对象列表,这些对象是从消费者轮询返回的所有 ConsumerRecord 实例转换而来的。 与批处理的 @KafkaListener 一样,KafkaHeaders.RECEIVED_KEYKafkaHeaders.RECEIVED_PARTITIONKafkaHeaders.RECEIVED_TOPICKafkaHeaders.OFFSET 头部也是列表,其位置与有效负载中的位置相对应。

收到的消息会填充某些头部。 有关更多信息,请参阅 KafkaHeaders

Consumer 对象(在 kafka_consumer 头部中)不是线程安全的。 你必须仅在适配器中调用监听器的线程上调用其方法。 如果你将消息传递给另一个线程,则不得调用其方法。

当提供了 retry-template 时,传递失败会根据其重试策略进行重试。 如果还提供了 error-channel,则在重试耗尽后,将使用默认的 ErrorMessageSendingRecoverer 作为恢复回调。 你也可以使用 recovery-callback 来指定在这种情况下采取的其他操作,或者将其设置为 null 以将最终异常抛给监听器容器,以便在那里处理。

在构建 ErrorMessage(用于 error-channelrecovery-callback)时,你可以通过设置 error-message-strategy 属性来自定义错误消息。 默认情况下,使用 RawRecordHeaderErrorMessageStrategy,以提供对转换后的消息以及原始 ConsumerRecord 的访问。

这种形式的重试是阻塞的,如果所有轮询记录的总重试延迟可能超过 max.poll.interval.ms 消费者属性,则可能会导致重新平衡。 相反,请考虑向监听器容器添加一个 DefaultErrorHandler,并配置一个 KafkaErrorSendingMessageRecoverer

配置

以下示例显示了如何配置消息驱动通道适配器:

  • Java DSL

  • Java

  • XML

@Bean
public IntegrationFlow topic1ListenerFromKafkaFlow() {
    return IntegrationFlow
            .from(Kafka.messageDrivenChannelAdapter(consumerFactory(),
                    KafkaMessageDrivenChannelAdapter.ListenerMode.record, TEST_TOPIC1)
                    .configureListenerContainer(c ->
                            c.ackMode(AbstractMessageListenerContainer.AckMode.MANUAL)
                                    .id("topic1ListenerContainer"))
                    .recoveryCallback(new ErrorMessageSendingRecoverer(errorChannel(),
                            new RawRecordHeaderErrorMessageStrategy()))
                    .retryTemplate(new RetryTemplate())
                    .filterInRetry(true))
            .filter(Message.class, m ->
                            m.getHeaders().get(KafkaHeaders.RECEIVED_MESSAGE_KEY, Integer.class) < 101,
                    f -> f.throwExceptionOnRejection(true))
            .<String, String>transform(String::toUpperCase)
            .channel(c -> c.queue("listeningFromKafkaResults1"))
            .get();
}
@Bean
public KafkaMessageDrivenChannelAdapter<String, String>
            adapter(KafkaMessageListenerContainer<String, String> container) {
    KafkaMessageDrivenChannelAdapter<String, String> kafkaMessageDrivenChannelAdapter =
            new KafkaMessageDrivenChannelAdapter<>(container, ListenerMode.record);
    kafkaMessageDrivenChannelAdapter.setOutputChannel(received());
    return kafkaMessageDrivenChannelAdapter;
}

@Bean
public KafkaMessageListenerContainer<String, String> container() throws Exception {
    ContainerProperties properties = new ContainerProperties(this.topic);
    // set more properties
    return new KafkaMessageListenerContainer<>(consumerFactory(), properties);
}

@Bean
public ConsumerFactory<String, String> consumerFactory() {
    Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, this.brokerAddress);
    // set more properties
    return new DefaultKafkaConsumerFactory<>(props);
}
<int-kafka:message-driven-channel-adapter
        id="kafkaListener"
        listener-container="container1"
        auto-startup="false"
        phase="100"
        send-timeout="5000"
        mode="record"
        retry-template="template"
        recovery-callback="callback"
        error-message-strategy="ems"
        channel="someChannel"
        error-channel="errorChannel" />

<bean id="container1" class="org.springframework.kafka.listener.KafkaMessageListenerContainer">
    <constructor-arg>
        <bean class="org.springframework.kafka.core.DefaultKafkaConsumerFactory">
            <constructor-arg>
                <map>
                <entry key="bootstrap.servers" value="localhost:9092" />
                ...
                </map>
            </constructor-arg>
        </bean>
    </constructor-arg>
    <constructor-arg>
        <bean class="org.springframework.kafka.listener.config.ContainerProperties">
            <constructor-arg name="topics" value="foo" />
        </bean>
    </constructor-arg>

</bean>

你还可以使用用于 @KafkaListener 注解的容器工厂来创建 ConcurrentMessageListenerContainer 实例用于其他目的。 有关示例,请参阅 Spring for Apache Kafka 文档

使用 Java DSL 时,容器不必配置为 @Bean,因为 DSL 将容器注册为 Bean。 以下示例显示了如何执行此操作:

@Bean
public IntegrationFlow topic2ListenerFromKafkaFlow() {
    return IntegrationFlow
            .from(Kafka.messageDrivenChannelAdapter(kafkaListenerContainerFactory().createContainer(TEST_TOPIC2),
            KafkaMessageDrivenChannelAdapter.ListenerMode.record)
                .id("topic2Adapter"))
            ...
            get();
}

请注意,在这种情况下,适配器会获得一个 id (topic2Adapter)。 容器以 topic2Adapter.container 的名称注册到应用程序上下文中。 如果适配器没有 id 属性,则容器的 bean 名称是容器的完全限定类名加上 #n,其中 n 会为每个容器递增。

入站通道适配器

KafkaMessageSource 提供了一个可轮询的通道适配器实现。

配置

  • Java DSL

  • Kotlin

  • Java

  • XML

@Bean
public IntegrationFlow flow(ConsumerFactory<String, String> cf)  {
    return IntegrationFlow.from(Kafka.inboundChannelAdapter(cf, new ConsumerProperties("myTopic")),
                          e -> e.poller(Pollers.fixedDelay(5000)))
            .handle(System.out::println)
            .get();
}
@Bean
fun sourceFlow(cf: ConsumerFactory<String, String>) =
    integrationFlow(Kafka.inboundChannelAdapter(cf,
        ConsumerProperties(TEST_TOPIC3).also {
            it.groupId = "kotlinMessageSourceGroup"
        }),
        { poller(Pollers.fixedDelay(100)) }) {
        handle { m ->

        }
    }
@InboundChannelAdapter(channel = "fromKafka", poller = @Poller(fixedDelay = "5000"))
@Bean
public KafkaMessageSource<String, String> source(ConsumerFactory<String, String> cf)  {
    ConsumerProperties consumerProperties = new ConsumerProperties("myTopic");
	consumerProperties.setGroupId("myGroupId");
	consumerProperties.setClientId("myClientId");
    retunr new KafkaMessageSource<>(cf, consumerProperties);
}
<int-kafka:inbound-channel-adapter
        id="adapter1"
        consumer-factory="consumerFactory"
        consumer-properties="consumerProperties1"
        ack-factory="ackFactory"
        channel="inbound"
        message-converter="converter"
        payload-type="java.lang.String"
        raw-header="true"
        auto-startup="false">
    <int:poller fixed-delay="5000"/>
</int-kafka:inbound-channel-adapter>

<bean id="consumerFactory" class="org.springframework.kafka.core.DefaultKafkaConsumerFactory">
    <constructor-arg>
        <map>
            <entry key="max.poll.records" value="1"/>
        </map>
    </constructor-arg>
</bean>

<bean id="consumerProperties1" class="org.springframework.kafka.listener.ConsumerProperties">
    <constructor-arg name="topics" value="topic1"/>
    <property name="groupId" value="group"/>
    <property name="clientId" value="client"/>
</bean>

请参阅 Javadoc 以获取可用属性。

默认情况下,max.poll.records 必须在消费者工厂中显式设置,否则如果消费者工厂是 DefaultKafkaConsumerFactory,它将被强制设置为 1。 你可以将属性 allowMultiFetch 设置为 true 来覆盖此行为。

你必须在 max.poll.interval.ms 内轮询消费者以避免重新平衡。 如果将 allowMultiFetch 设置为 true,则必须处理所有检索到的记录,并在 max.poll.interval.ms 内再次轮询。

此适配器发出的消息包含一个 kafka_remainingRecords 头部,其中包含上一次轮询剩余的记录计数。

6.2 版本开始,KafkaMessageSource 支持消费者属性中提供的 ErrorHandlingDeserializerDeserializationException 从记录头部中提取并抛出给调用者。 使用 SourcePollingChannelAdapter 时,此异常会包装到 ErrorMessage 中并发布到其 errorChannel。 有关更多信息,请参阅 ErrorHandlingDeserializer 文档。

出站网关

出站网关用于请求/回复操作。 它与大多数 Spring Integration 网关的不同之处在于,发送线程不会在网关中阻塞,并且回复在回复监听器容器线程上处理。 如果你的代码通过同步 消息网关 调用网关,则用户线程将在那里阻塞,直到收到回复(或发生超时)。

KafkaProducerMessageHandlersendTimeoutExpression 默认值已从 10 秒更改为 delivery.timeout.ms Kafka 生产者属性 + 5000,以便在超时后将实际的 Kafka 错误传播到应用程序,而不是由该框架生成的超时。 此更改是为了保持一致性,因为你可能会遇到意外行为(Spring 可能会使 send() 超时,但实际上最终会成功)。 重要提示:该超时默认为 120 秒,因此你可能希望缩短它以获得更及时的失败。

配置

以下示例显示了如何配置网关:

  • Java DSL

  • Java

  • XML

@Bean
public IntegrationFlow outboundGateFlow(
        ReplyingKafkaTemplate<String, String, String> kafkaTemplate) {

    return IntegrationFlow.from("kafkaRequests")
            .handle(Kafka.outboundGateway(kafkaTemplate))
            .channel("kafkaReplies")
            .get();
}
@Bean
@ServiceActivator(inputChannel = "kafkaRequests", outputChannel = "kafkaReplies")
public KafkaProducerMessageHandler<String, String> outGateway(
        ReplyingKafkaTemplate<String, String, String> kafkaTemplate) {
    return new KafkaProducerMessageHandler<>(kafkaTemplate);
}
<int-kafka:outbound-gateway
    id="allProps"
    error-message-strategy="ems"
    kafka-template="template"
    message-key-expression="'key'"
    order="23"
    partition-id-expression="2"
    reply-channel="replies"
    reply-timeout="43"
    request-channel="requests"
    requires-reply="false"
    send-success-channel="successes"
    send-failure-channel="failures"
    send-timeout-expression="44"
    sync="true"
    timestamp-expression="T(System).currentTimeMillis()"
    topic-expression="'topic'"/>

请参阅 Javadoc 以获取可用属性。

请注意,使用的类与 kafka-outbound 相同,唯一的区别是传递给构造函数的 KafkaTemplateReplyingKafkaTemplate。 有关更多信息,请参阅 Spring for Apache Kafka 文档

出站主题、分区、键等以与出站适配器相同的方式确定。 回复主题的确定方式如下:

  1. 名为 KafkaHeaders.REPLY_TOPIC 的消息头(如果存在,它必须具有 Stringbyte[] 值)将根据模板的回复容器的订阅主题进行验证。

  2. 如果模板的 replyContainer 仅订阅了一个主题,则使用该主题。

你还可以指定 KafkaHeaders.REPLY_PARTITION 头部来确定用于回复的特定分区。 同样,这会根据模板的回复容器的订阅进行验证。

或者,你也可以使用类似于以下 bean 的配置:

@Bean
public IntegrationFlow outboundGateFlow() {
    return IntegrationFlow.from("kafkaRequests")
            .handle(Kafka.outboundGateway(producerFactory(), replyContainer())
                .configureKafkaTemplate(t -> t.replyTimeout(30_000)))
            .channel("kafkaReplies")
            .get();
}

入站网关

入站网关用于请求/回复操作。

配置

以下示例显示了如何配置入站网关:

  • Java DSL

  • Java

  • XML

@Bean
public IntegrationFlow serverGateway(
        ConcurrentMessageListenerContainer<Integer, String> container,
        KafkaTemplate<Integer, String> replyTemplate) {
    return IntegrationFlow
            .from(Kafka.inboundGateway(container, replyTemplate)
                .replyTimeout(30_000))
            .<String, String>transform(String::toUpperCase)
            .get();
}
@Bean
public KafkaInboundGateway<Integer, String, String> inboundGateway(
        AbstractMessageListenerContainer<Integer, String>container,
        KafkaTemplate<Integer, String> replyTemplate) {

    KafkaInboundGateway<Integer, String, String> gateway =
        new KafkaInboundGateway<>(container, replyTemplate);
    gateway.setRequestChannel(requests);
    gateway.setReplyChannel(replies);
    gateway.setReplyTimeout(30_000);
    return gateway;
}
<int-kafka:inbound-gateway
        id="gateway1"
        listener-container="container1"
        kafka-template="template"
        auto-startup="false"
        phase="100"
        request-timeout="5000"
        request-channel="nullChannel"
        reply-channel="errorChannel"
        reply-timeout="43"
        message-converter="messageConverter"
        payload-type="java.lang.String"
        error-message-strategy="ems"
        retry-template="retryTemplate"
        recovery-callback="recoveryCallback"/>

请参阅 Javadoc 以获取可用属性。

当提供了 RetryTemplate 时,传递失败会根据其重试策略进行重试。 如果还提供了 error-channel,则在重试耗尽后,将使用默认的 ErrorMessageSendingRecoverer 作为恢复回调。 你也可以使用 recovery-callback 来指定在这种情况下采取的其他操作,或者将其设置为 null 以将最终异常抛给监听器容器,以便在那里处理。

在构建 ErrorMessage(用于 error-channelrecovery-callback)时,你可以通过设置 error-message-strategy 属性来自定义错误消息。 默认情况下,使用 RawRecordHeaderErrorMessageStrategy,以提供对转换后的消息以及原始 ConsumerRecord 的访问。

这种形式的重试是阻塞的,如果所有轮询记录的总重试延迟可能超过 max.poll.interval.ms 消费者属性,则可能会导致重新平衡。 相反,请考虑向监听器容器添加一个 DefaultErrorHandler,并配置一个 KafkaErrorSendingMessageRecoverer

以下示例显示了如何使用 Java DSL 配置一个简单的转换为大写的功能:

或者,你可以使用类似于以下代码来配置一个转换为大写的功能:

@Bean
public IntegrationFlow serverGateway() {
    return IntegrationFlow
            .from(Kafka.inboundGateway(consumerFactory(), containerProperties(),
                    producerFactory())
                .replyTimeout(30_000))
            .<String, String>transform(String::toUpperCase)
            .get();
}

你还可以使用用于 @KafkaListener 注解的容器工厂来创建 ConcurrentMessageListenerContainer 实例用于其他目的。 有关示例,请参阅 Spring for Apache Kafka 文档kafka-inbound

由 Apache Kafka 主题支持的通道

Spring Integration 具有由 Apache Kafka 主题支持的 MessageChannel 实现,用于持久化。

每个通道都需要一个 KafkaTemplate 用于发送端,以及一个监听器容器工厂(用于可订阅通道)或一个 KafkaMessageSource 用于可轮询通道。

Java DSL 配置

  • Java DSL

  • Java

  • XML

@Bean
public IntegrationFlow flowWithSubscribable(KafkaTemplate<Integer, String> template,
        ConcurrentKafkaListenerContainerFactory<Integer, String> containerFactory) {

    return IntegrationFlow.from(...)
            ...
            .channel(Kafka.channel(template, containerFactory, "someTopic1").groupId("group1"))
            ...
            .get();
}

@Bean
public IntegrationFlow flowWithPubSub(KafkaTemplate<Integer, String> template,
        ConcurrentKafkaListenerContainerFactory<Integer, String> containerFactory) {

    return IntegrationFlow.from(...)
            ...
            .publishSubscribeChannel(pubSub(template, containerFactory),
                pubsub -> pubsub
                            .subscribe(subflow -> ...)
                            .subscribe(subflow -> ...))
            .get();
}

@Bean
public BroadcastCapableChannel pubSub(KafkaTemplate<Integer, String> template,
        ConcurrentKafkaListenerContainerFactory<Integer, String> containerFactory) {

    return Kafka.publishSubscribeChannel(template, containerFactory, "someTopic2")
            .groupId("group2")
            .get();
}

@Bean
public IntegrationFlow flowWithPollable(KafkaTemplate<Integer, String> template,
        KafkaMessageSource<Integer, String> source) {

    return IntegrationFlow.from(...)
            ...
            .channel(Kafka.pollableChannel(template, source, "someTopic3").groupId("group3"))
            .handle(...,  e -> e.poller(...))
            ...
            .get();
}
/**
 * Channel for a single subscriber.
 **/
@Bean
SubscribableKafkaChannel pointToPoint(KafkaTemplate<String, String> template,
    KafkaListenerContainerFactory<String, String> factory)

    SubscribableKafkaChannel channel =
        new SubscribableKafkaChannel(template, factory, "topicA");
    channel.setGroupId("group1");
    return channel;
}

/**
 * Channel for multiple subscribers.
 **/
@Bean
SubscribableKafkaChannel pubsub(KafkaTemplate<String, String> template,
    KafkaListenerContainerFactory<String, String> factory)

    SubscribableKafkaChannel channel =
        new SubscribableKafkaChannel(template, factory, "topicB", true);
    channel.setGroupId("group2");
    return channel;
}

/**
 * Pollable channel (topic is configured on the source)
 **/
@Bean
PollableKafkaChannel pollable(KafkaTemplate<String, String> template,
    KafkaMessageSource<String, String> source)

    PollableKafkaChannel channel =
        new PollableKafkaChannel(template, source);
    channel.setGroupId("group3");
    return channel;
}
<int-kafka:channel kafka-template="template" id="ptp" topic="ptpTopic" group-id="ptpGroup"
    container-factory="containerFactory" />

<int-kafka:pollable-channel kafka-template="template" id="pollable" message-source="source"
    group-id = "pollableGroup"/>

<int-kafka:publish-subscribe-channel kafka-template="template" id="pubSub" topic="pubSubTopic"
    group-id="pubSubGroup" container-factory="containerFactory" />

消息转换

提供了 StringJsonMessageConverter。 有关更多信息,请参阅 Spring for Apache Kafka 文档

当使用此转换器和消息驱动通道适配器时,你可以指定希望传入有效负载转换成的类型。 这可以通过在适配器上设置 payload-type 属性(payloadType 属性)来实现。 以下示例显示了如何在 XML 配置中执行此操作:

<int-kafka:message-driven-channel-adapter
        id="kafkaListener"
        listener-container="container1"
        auto-startup="false"
        phase="100"
        send-timeout="5000"
        channel="nullChannel"
        message-converter="messageConverter"
        payload-type="com.example.Thing"
        error-channel="errorChannel" />

<bean id="messageConverter"
    class="org.springframework.kafka.support.converter.MessagingMessageConverter"/>

以下示例显示了如何在 Java 配置中在适配器上设置 payload-type 属性(payloadType 属性):

@Bean
public KafkaMessageDrivenChannelAdapter<String, String>
            adapter(KafkaMessageListenerContainer<String, String> container) {
    KafkaMessageDrivenChannelAdapter<String, String> kafkaMessageDrivenChannelAdapter =
            new KafkaMessageDrivenChannelAdapter<>(container, ListenerMode.record);
    kafkaMessageDrivenChannelAdapter.setOutputChannel(received());
    kafkaMessageDrivenChannelAdapter.setMessageConverter(converter());
    kafkaMessageDrivenChannelAdapter.setPayloadType(Thing.class);
    return kafkaMessageDrivenChannelAdapter;
}

空有效负载和日志压缩“墓碑”记录

Spring Messaging Message<?> 对象不能具有 null 有效负载。 当使用 Apache Kafka 的端点时,null 有效负载(也称为墓碑记录)由类型为 KafkaNull 的有效负载表示。 有关更多信息,请参阅 Spring for Apache Kafka 文档

Spring Integration 端点的 POJO 方法可以使用真正的 null 值而不是 KafkaNull。 为此,请使用 @Payload(required = false) 标记参数。 以下示例显示了如何执行此操作:

@ServiceActivator(inputChannel = "fromSomeKafkaInboundEndpoint")
public void in(@Header(KafkaHeaders.RECEIVED_KEY) String key,
               @Payload(required = false) Customer customer) {
    // customer is null if a tombstone record
    ...
}

KStream 调用 Spring Integration 流

你可以使用 MessagingTransformerKStream 调用集成流:

@Bean
public KStream<byte[], byte[]> kStream(StreamsBuilder kStreamBuilder,
        MessagingTransformer<byte[], byte[], byte[]> transformer)  transformer) {
    KStream<byte[], byte[]> stream = kStreamBuilder.stream(STREAMING_TOPIC1);
    stream.mapValues((ValueMapper<byte[], byte[]>) String::toUpperCase)
            ...
            .transform(() -> transformer)
            .to(streamingTopic2);

    stream.print(Printed.toSysOut());

    return stream;
}

@Bean
@DependsOn("flow")
public MessagingTransformer<byte[], byte[], String> transformer(
        MessagingFunction function) {

    MessagingMessageConverter converter = new MessagingMessageConverter();
    converter.setHeaderMapper(new SimpleKafkaHeaderMapper("*"));
    return new MessagingTransformer<>(function, converter);
}

@Bean
public IntegrationFlow flow() {
    return IntegrationFlow.from(MessagingFunction.class)
        ...
        .get();
}

当集成流以接口开始时,创建的代理的名称是流 bean 的名称,并附加 ".gateway",因此此 bean 名称可以在需要时用作 @Qualifier

读/处理/写场景的性能考虑

许多应用程序从主题消费,执行一些处理并写入另一个主题。 在大多数情况下,如果 write 失败,应用程序希望抛出异常,以便可以重试传入请求或将其发送到死信主题。 此功能由底层消息监听器容器以及配置合适的错误处理器支持。 但是,为了支持此功能,我们需要阻塞监听器线程,直到写入操作成功(或失败),以便可以将任何异常抛给容器。 在消费单个记录时,这通过在出站适配器上设置 sync 属性来实现。 但是,在消费批次时,使用 sync 会导致显著的性能下降,因为应用程序会在发送下一条消息之前等待每次发送的结果。 你还可以执行多次发送,然后等待这些发送的结果。 这通过向消息处理器添加 futuresChannel 来实现。 要启用该功能,请将 KafkaIntegrationHeaders.FUTURE_TOKEN 添加到出站消息中;然后可以使用它将 Future 与特定的已发送消息关联起来。 以下是一个如何使用此功能的示例:

@SpringBootApplication
public class FuturesChannelApplication {

    public static void main(String[] args) {
        SpringApplication.run(FuturesChannelApplication.class, args);
    }

    @Bean
    IntegrationFlow inbound(ConsumerFactory<String, String> consumerFactory, Handler handler) {
        return IntegrationFlow.from(Kafka.messageDrivenChannelAdapter(consumerFactory,
                    ListenerMode.batch, "inTopic"))
                .handle(handler)
                .get();
    }

    @Bean
    IntegrationFlow outbound(KafkaTemplate<String, String> kafkaTemplate) {
        return IntegrationFlow.from(Gate.class)
                .enrichHeaders(h -> h
                        .header(KafkaHeaders.TOPIC, "outTopic")
                        .headerExpression(KafkaIntegrationHeaders.FUTURE_TOKEN, "headers[id]"))
                .handle(Kafka.outboundChannelAdapter(kafkaTemplate)
                        .futuresChannel("futures"))
                .get();
    }

    @Bean
    PollableChannel futures() {
        return new QueueChannel();
    }

}

@Component
@DependsOn("outbound")
class Handler {

    @Autowired
    Gate gate;

    @Autowired
    PollableChannel futures;

    public void handle(List<String> input) throws Exception {
        System.out.println(input);
        input.forEach(str -> this.gate.send(str.toUpperCase()));
        for (int i = 0; i < input.size(); i++) {
            Message<?> future = this.futures.receive(10000);
            ((Future<?>) future.getPayload()).get(10, TimeUnit.SECONDS);
        }
    }

}

interface Gate {

    void send(String out);

}