使用協定配接器
到目前為止顯示的所有範例都說明了 DSL 如何透過使用 Spring Integration 程式設計模型來支援訊息傳遞架構。然而,我們尚未進行任何實際的整合。這樣做需要透過 HTTP、JMS、AMQP、TCP、JDBC、FTP、SMTP 等存取遠端資源,或存取本機檔案系統。Spring Integration 支援所有這些以及更多。理想情況下,DSL 應該為所有這些提供一流的支援,但實作所有這些並在新的配接器新增到 Spring Integration 時保持同步是一項艱鉅的任務。因此,期望 DSL 持續趕上 Spring Integration 的發展。
因此,我們提供高階 API,以無縫定義協定特定的訊息傳遞。我們透過工廠和建構器模式以及 Lambda 來做到這一點。您可以將工廠類別視為「命名空間工廠」,因為它們扮演的角色與具體協定特定的 Spring Integration 模組的 XML 命名空間相同。目前,Spring Integration Java DSL 支援 Amqp
、Feed
、Jms
、Files
、(S)Ftp
、Http
、JPA
、MongoDb
、TCP/UDP
、Mail
、WebFlux
和 Scripts
命名空間工廠。以下範例示範如何使用其中三個(Amqp
、Jms
和 Mail
):
@Bean
public IntegrationFlow amqpFlow() {
return IntegrationFlow.from(Amqp.inboundGateway(this.rabbitConnectionFactory, queue()))
.transform("hello "::concat)
.transform(String.class, String::toUpperCase)
.get();
}
@Bean
public IntegrationFlow jmsOutboundGatewayFlow() {
return IntegrationFlow.from("jmsOutboundGatewayChannel")
.handle(Jms.outboundGateway(this.jmsConnectionFactory)
.replyContainer(c ->
c.concurrentConsumers(3)
.sessionTransacted(true))
.requestDestination("jmsPipelineTest"))
.get();
}
@Bean
public IntegrationFlow sendMailFlow() {
return IntegrationFlow.from("sendMailChannel")
.handle(Mail.outboundAdapter("localhost")
.port(smtpPort)
.credentials("user", "pw")
.protocol("smtp")
.javaMailProperties(p -> p.put("mail.debug", "true")),
e -> e.id("sendMailEndpoint"))
.get();
}
前面的範例示範如何將「命名空間工廠」用作內嵌配接器宣告。但是,您可以從 @Bean
定義中使用它們,以使 IntegrationFlow
方法鏈更具可讀性。
在我們花費精力在其他命名空間工廠之前,我們正在徵求社群對這些命名空間工廠的回饋。我們也感謝您對我們接下來應該支援哪些配接器和閘道器的優先順序提供任何意見。 |
您可以在本參考手冊的協定特定章節中找到更多 Java DSL 範例。
所有其他協定通道配接器都可以設定為通用 Bean,並連接到 IntegrationFlow
,如下列範例所示:
@Bean
public QueueChannelSpec wrongMessagesChannel() {
return MessageChannels
.queue()
.wireTap("wrongMessagesWireTapChannel");
}
@Bean
public IntegrationFlow xpathFlow(MessageChannel wrongMessagesChannel) {
return IntegrationFlow.from("inputChannel")
.filter(new StringValueTestXPathMessageSelector("namespace-uri(/*)", "my:namespace"),
e -> e.discardChannel(wrongMessagesChannel))
.log(LoggingHandler.Level.ERROR, "test.category", m -> m.getHeaders().getId())
.route(xpathRouter(wrongMessagesChannel))
.get();
}
@Bean
public AbstractMappingMessageRouter xpathRouter(MessageChannel wrongMessagesChannel) {
XPathRouter router = new XPathRouter("local-name(/*)");
router.setEvaluateAsString(true);
router.setResolutionRequired(false);
router.setDefaultOutputChannel(wrongMessagesChannel);
router.setChannelMapping("Tags", "splittingChannel");
router.setChannelMapping("Tag", "receivedChannel");
return router;
}