跳到主要内容
版本:7.0.2

消息桥接

DeepSeek V3 中英对照 Messaging Bridge

消息桥接器是一种相对简单的端点,用于连接两个消息通道或通道适配器。例如,您可能希望将 PollableChannel 连接到 SubscribableChannel,这样订阅端点就不必担心任何轮询配置。相反,消息桥接器会提供轮询配置。

通过在两个通道之间提供一个中间轮询器,您可以使用消息桥接来限制入站消息的速率。轮询器的触发器决定了消息到达第二个通道的速率,而轮询器的 maxMessagesPerPoll 属性则对吞吐量施加了限制。

消息桥的另一个有效用途是连接两个不同的系统。在这种场景下,Spring Integration 的作用仅限于建立系统间的连接,并在必要时管理轮询器。更常见的情况是在两个系统之间至少配置一个转换器,以实现格式间的转换。此时,通道可以作为转换器端点的 input-channeloutput-channel 提供。如果不需要数据格式转换,消息桥可能确实就足够了。

使用 XML 配置网桥

您可以使用 <bridge> 元素在两个消息通道或通道适配器之间创建消息桥接。为此,请提供 input-channeloutput-channel 属性,如下例所示:

<int:bridge input-channel="input" output-channel="output"/>

如上所述,消息桥的一个常见用例是将 PollableChannel 连接到 SubscribableChannel。在执行此角色时,消息桥还可以充当节流器:

<int:bridge input-channel="pollable" output-channel="subscribable">
<int:poller max-messages-per-poll="10" fixed-rate="5000"/>
</int:bridge>

您可以使用类似的机制来连接通道适配器。以下示例展示了 Spring Integration stream 命名空间中 stdinstdout 适配器之间的简单“回显”:

<int-stream:stdin-channel-adapter id="stdin"/>

<int-stream:stdout-channel-adapter id="stdout"/>

<int:bridge id="echo" input-channel="stdin" output-channel="stdout"/>

类似的配置也适用于其他(可能更有用的)通道适配器桥接,例如文件到 JMS 或邮件到文件。接下来的章节将介绍各种通道适配器。

备注

如果在桥接器上没有定义 'output-channel',则会使用入站消息提供的回复通道(如果可用)。如果既没有输出通道也没有回复通道可用,则会抛出异常。

使用 Java 配置配置桥接器

以下示例展示了如何使用 @BridgeFrom 注解在 Java 中配置桥接:

@Bean
public PollableChannel polled() {
return new QueueChannel();
}

@Bean
@BridgeFrom(value = "polled", poller = @Poller(fixedDelay = "5000", maxMessagesPerPoll = "10"))
public SubscribableChannel direct() {
return new DirectChannel();
}

以下示例展示了如何使用 @BridgeTo 注解在 Java 中配置桥接:

@Bean
@BridgeTo(value = "direct", poller = @Poller(fixedDelay = "5000", maxMessagesPerPoll = "10"))
public PollableChannel polled() {
return new QueueChannel();
}

@Bean
public SubscribableChannel direct() {
return new DirectChannel();
}

或者,你也可以使用 BridgeHandler,如下例所示:

@Bean
@ServiceActivator(inputChannel = "polled",
poller = @Poller(fixedRate = "5000", maxMessagesPerPoll = "10"))
public BridgeHandler bridge() {
BridgeHandler bridge = new BridgeHandler();
bridge.setOutputChannelName("direct");
return bridge;
}

使用 Java DSL 配置桥接器

您可以使用 Java 领域特定语言(DSL)来配置桥接器,如下例所示:

@Bean
public IntegrationFlow bridgeFlow() {
return IntegrationFlow.from("polled")
.bridge(e -> e.poller(Pollers.fixedDelay(5000).maxMessagesPerPoll(10)))
.channel("direct")
.get();
}