Apache Kafka 支持
Apache Kafka 支持
概述
Spring Integration for Apache Kafka 基于 Spring for Apache Kafka 项目。
您需要将此依赖项包含在您的项目中:
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-kafka</artifactId>
<version>6.0.9</version>
</dependency>
compile "org.springframework.integration:spring-integration-kafka:6.0.9"
它提供以下组件:
出站通道适配器
出站通道适配器用于将消息从 Spring 集成通道发布到 Apache Kafka 主题。 通道在应用程序上下文中定义,然后连接到向 Apache Kafka 发送消息的应用程序。 发送方应用程序可以使用 Spring 集成消息发布到 Apache Kafka,这些消息由出站通道适配器在内部转换为 Kafka 记录,如下所示:
-
Spring Integration 消息的有效负载用于填充 Kafka 记录的有效负载。
-
默认情况下,
kafka_messageKey
Spring Integration 消息的标头用于填充 Kafka 记录的键。
您可以自定义目标 topic 和 partition 以通过kafka_topic
和kafka_partitionId
标头。
此外,<int-kafka:outbound-channel-adapter>
提供了通过在出站消息上应用 SPEL 表达式来提取键、目标主题和目标分区的功能。
为此,它支持三对互斥的属性:
-
topic
和topic-expression
-
message-key
和message-key-expression
-
partition-id
和partition-id-expression
这些允许您指定topic
,message-key
和partition-id
分别作为适配器上的静态值,或在运行时根据请求消息动态评估其值。
这KafkaHeaders interface(由spring-kafka ) 包含用于与
头。
这messageKey 和topic 默认标头现在需要kafka_ 前缀。
从使用旧标头的早期版本迁移时,您需要指定message-key-expression="headers['messageKey']" 和topic-expression="headers['topic']" 在<int-kafka:outbound-channel-adapter> .
或者,您可以将上游的标头更改为新的 HeadersKafkaHeaders 通过使用<header-enricher> 或MessageBuilder .
如果使用常量值,则还可以使用topic 和message-key . |
注意 : 如果适配器配置了主题或消息键(带有常量或表达式),则使用它们并忽略相应的标头。 如果您希望 Headers 覆盖配置,则需要在表达式中对其进行配置,如下所示:
topic-expression="headers['topic'] != null ? headers['topic'] : 'myTopic'"
该适配器需要一个KafkaTemplate
,这反过来又需要适当配置的KafkaProducerFactory
.
如果send-failure-channel
(sendFailureChannel
),并且send()
failure (sync 或 async) 收到,则会收到ErrorMessage
将发送到频道。
有效负载是一个KafkaSendFailureException
跟failedMessage
,record
(ProducerRecord
) 和cause
性能。
您可以覆盖DefaultErrorMessageStrategy
通过设置error-message-strategy
财产。
如果send-success-channel
(sendSuccessChannel
),则有效负载为org.apache.kafka.clients.producer.RecordMetadata
在成功发送后发送。
如果您的应用程序使用事务,并且使用相同的通道适配器来发布消息,其中事务由侦听器容器启动,以及在没有现有事务的情况下发布消息,则必须配置transactionIdPrefix 在KafkaTemplate 覆盖容器或事务管理器使用的前缀。
容器启动的事务使用的前缀(生产者工厂或事务管理器属性)在所有应用程序实例上必须相同。
用于仅限生产者事务的前缀在所有应用程序实例上必须是唯一的。 |
您可以配置flushExpression
它必须解析为布尔值。
如果您在使用linger.ms
和batch.size
Kafka 生产者属性;表达式的计算结果应为Boolean.TRUE
在最后一条消息中,将立即发送不完整的批处理。
默认情况下,表达式会查找Boolean
值在KafkaIntegrationHeaders.FLUSH
标头 (kafka_flush
).
如果值为true
如果是false
或标头不存在。
这KafkaProducerMessageHandler.sendTimeoutExpression
default 已从 10 秒更改为delivery.timeout.ms
Kafka 生产者属性+ 5000
以便将超时后的实际 Kafka 错误传播到应用程序,而不是此框架生成的超时。
为了保持一致性,对此进行了更改,因为您可能会遇到意外的行为(Spring 可能会超时发送,而实际上最终会成功)。
重要说明:默认情况下,该超时为 120 秒,因此您可能希望减少它以获得更及时的故障。
配置
以下示例说明如何为 Apache Kafka 配置出站通道适配器:
@Bean
public ProducerFactory<Integer, String> producerFactory() {
return new DefaultKafkaProducerFactory<>(KafkaTestUtils.producerProps(embeddedKafka));
}
@Bean
public IntegrationFlow sendToKafkaFlow() {
return f -> f
.<String>split(p -> Stream.generate(() -> p).limit(101).iterator(), null)
.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-kafka
KafkaMessageListenerContainer
或ConcurrentListenerContainer
.
此外,mode
属性可用。
它可以接受record
或batch
(默认:record
).
为record
模式中,每个消息有效负载都会从单个ConsumerRecord
.
为batch
模式中,payload 是从所有ConsumerRecord
使用者轮询返回的实例。
与批处理的@KafkaListener
这KafkaHeaders.RECEIVED_KEY
,KafkaHeaders.RECEIVED_PARTITION
,KafkaHeaders.RECEIVED_TOPIC
和KafkaHeaders.OFFSET
headers 也是列表,其位置对应于有效负载中的位置。
收到的邮件会填充某些标头。
请参阅KafkaHeaders
类了解更多信息。
这Consumer object(在kafka_consumer header) 不是线程安全的。
您只能在调用适配器中的侦听器的线程上调用其方法。
如果将消息移交给另一个线程,则不得调用其方法。 |
当retry-template
,则根据其重试策略重试传递失败。
如果error-channel
,则默认的ErrorMessageSendingRecoverer
将用作重试次数用尽后的恢复回调。
您还可以使用recovery-callback
以指定在这种情况下要采取的其他作,或将其设置为null
将最终异常抛出给侦听器容器,以便在那里进行处理。
在构建ErrorMessage
(用于error-channel
或recovery-callback
),您可以通过设置error-message-strategy
财产。
默认情况下,RawRecordHeaderErrorMessageStrategy
用于提供对已转换消息以及原始ConsumerRecord
.
这种形式的重试是阻塞的,如果所有轮询记录的聚合重试延迟可能超过max.poll.interval.ms consumer 属性。
相反,请考虑添加DefaultErrorHandler 添加到侦听器容器中,配置了KafkaErrorSendingMessageRecoverer . |
配置
以下示例说明如何配置消息驱动的通道适配器:
@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
提供 pollable 通道适配器实现。
配置
@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>
请参阅 javadocs 了解可用属性。
默认情况下,max.poll.records
必须在 Consumer Factory 中显式设置,或者如果 Consumer Factory 是DefaultKafkaConsumerFactory
.
您可以设置属性allowMultiFetch
自true
以覆盖此行为。
您必须在max.poll.interval.ms 以避免重新平衡。
如果您将allowMultiFetch 自true 您必须处理所有检索到的记录,并在max.poll.interval.ms . |
此适配器发出的消息包含报头kafka_remainingRecords
包含上一次轮询的剩余记录计数。
出站网关
出站网关用于请求/回复作。 它与大多数 Spring 集成网关的不同之处在于,发送线程不会在网关中阻塞,并且回复是在回复侦听器容器线程上处理的。 如果您的代码调用同步 Messaging Gateway 后面的网关,则用户线程将阻塞该网关,直到收到回复(或发生超时)。
在为回复容器分配其主题和分区之前,网关不接受请求。
建议您添加ConsumerRebalanceListener 添加到模板的回复容器属性中,并等待onPartitionsAssigned call 调用。 |
这KafkaProducerMessageHandler
sendTimeoutExpression
默认值为delivery.timeout.ms
Kafka 生产者属性+ 5000
以便将超时后的实际 Kafka 错误传播到应用程序,而不是此框架生成的超时。
为了保持一致性,此更改已更改,因为您可能会遇到意外行为(Spring 可能会使send()
,而实际上最终是成功的)。
重要说明:默认情况下,该超时为 120 秒,因此您可能希望减少它以获得更及时的故障。
配置
以下示例显示如何配置网关:
@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'"/>
请参阅 javadocs 了解可用属性。
请注意,使用与出站通道适配器相同的类,唯一的区别是KafkaTemplate
传递给构造函数的是一个ReplyingKafkaTemplate
.
有关更多信息,请参阅 Spring for Apache Kafka 文档。
出站主题、分区、键等的确定方式与出站适配器相同。 回复主题确定如下:
-
名为
KafkaHeaders.REPLY_TOPIC
(如果存在,则必须具有String
或byte[]
值)根据模板的回复容器的订阅主题进行验证。 -
如果模板的
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();
}
入站网关
入站网关用于请求/回复作。
配置
以下示例显示如何配置入站网关:
@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"/>
请参阅 javadocs 了解可用属性。
当RetryTemplate
,则根据其重试策略重试传递失败。
如果error-channel
,则默认的ErrorMessageSendingRecoverer
将用作重试次数用尽后的恢复回调。
您还可以使用recovery-callback
以指定在这种情况下要采取的其他作,或将其设置为null
将最终异常抛出给侦听器容器,以便在那里进行处理。
在构建ErrorMessage
(用于error-channel
或recovery-callback
),您可以通过设置error-message-strategy
财产。
默认情况下,RawRecordHeaderErrorMessageStrategy
用于提供对已转换消息以及原始ConsumerRecord
.
这种形式的重试是阻塞的,如果所有轮询记录的聚合重试延迟可能超过max.poll.interval.ms consumer 属性。
相反,请考虑添加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 文档和消息驱动的通道适配器。
Apache Kafka 支持的通道主题
Spring 集成具有MessageChannel
由 Apache Kafka 主题支持的实现以实现持久性。
每个通道都需要一个KafkaTemplate
对于发送端和侦听器容器工厂(用于可订阅频道)或KafkaMessageSource
对于可轮询通道。
Java DSL 配置
@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
属性)的 Package。
以下示例显示了如何在 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"/>
以下示例演示如何设置payload-type
属性 (payloadType
属性)的 Java 配置中:
@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;
}
Null 负载和日志压缩“Tombstone”记录
Spring 消息传递Message<?>
对象不能具有null
负载。
当您使用 Apache Kafka 的终端节点时,null
有效负载 (也称为逻辑删除记录) 由 类型KafkaNull
.
有关更多信息,请参阅 Spring for Apache Kafka 文档。
Spring 集成端点的 POJO 方法可以使用 truenull
value 而不是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
您可以使用MessagingTransformer
要从KStream
:
@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
属性。
但是,在使用 batch 时,使用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);
}