对于最新稳定版本,请使用 Spring Integration 7.0.0spring-doc.cadn.net.cn

消息桥接器

消息桥接是一种相对简单的端点,连接两个消息通道或通道适配器。 例如,你可能想连接一个Pollable频道转给订阅频道这样订阅端点就不用担心任何轮询配置。 相反,消息桥提供轮询配置。spring-doc.cadn.net.cn

通过在两个信道之间提供一个中介轮询器,你可以使用消息桥来限制进站消息的传输速度。 轮询器的触发器决定消息到达第二个信道的速率,轮询器的maxMessagesPerPoll属性强制执行吞吐量的限制。spring-doc.cadn.net.cn

消息桥的另一个有效用途是连接两个不同的系统。 在这种情况下,Spring Integration 的作用仅限于连接这些系统并在必要时管理轮询器。 更常见的是,两个系统之间至少有一个变换器,以便在它们的格式之间进行转换。 在这种情况下,通道可以作为转换器端点的“输入通道”和“输出通道”提供。 如果不需要数据格式转换,消息桥可能确实足够。spring-doc.cadn.net.cn

用XML配置桥接器

你可以使用<桥>Element用于在两个消息通道或通道适配器之间建立消息桥接。 为此,请提供输入通道输出通道属性,如下例所示:spring-doc.cadn.net.cn

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

如上所述,消息桥接的一个常见用例是连接Pollable频道转给订阅频道. 在执行此功能时,消息桥也可以作为节流器:spring-doc.cadn.net.cn

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

你可以用类似的连接方式连接通道适配器。 以下示例展示了简单的“回声”标准学生来自 Spring Integration 的适配器Namespace:spring-doc.cadn.net.cn

<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或邮件到文件。 接下来的章节将介绍各种通道适配器。spring-doc.cadn.net.cn

如果桥接器上没有定义“输出通道”,则使用由入站消息提供的回复通道(如有)。 如果既没有输出也没有回应通道,则会抛出异常。

用 Java 配置配置桥接器

以下示例展示了如何通过使用@BridgeFrom注解:spring-doc.cadn.net.cn

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

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

以下示例展示了如何通过使用@BridgeTo注解:spring-doc.cadn.net.cn

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

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

或者,你也可以使用桥接处理者,如下示例所示:spring-doc.cadn.net.cn

@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)来配置桥接器,如下示例所示:spring-doc.cadn.net.cn

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