Spring Integration 4.0:完整的无XML示例
1.簡介
Spring Integration 4.0終于發(fā)布了 ,并且此版本具有非常好的功能。 本文介紹的一種可能性是完全不使用XML即可配置集成流程。 那些不喜歡XML的人僅使用JavaConfig就可以開發(fā)集成應(yīng)用程序。
本文分為以下幾節(jié):
- 源代碼可以在github上找到。
- 在此示例中調(diào)用的Web服務(wù)的源代碼可以在github的spring-samples存儲庫中找到。
2.流程概述
該示例應(yīng)用程序顯示了如何配置多個消息傳遞和集成端點。 用戶通過指定課程ID來請求課程。 該流程將調(diào)用Web服務(wù),并將響應(yīng)返回給用戶。 此外,某些類型的課程將存儲到數(shù)據(jù)庫中。
流程如下:
- 集成網(wǎng)關(guān) (課程服務(wù))用作消息傳遞系統(tǒng)的入口。
- 轉(zhuǎn)換器根據(jù)用戶指定的課程ID生成請求消息。
- Web服務(wù)出站網(wǎng)關(guān)將請求發(fā)送到Web服務(wù)并等待響應(yīng)。
- 服務(wù)激活器訂閱了響應(yīng)通道,以便將課程名稱返回給用戶。
- 過濾器也訂閱了響應(yīng)通道。 此過濾器會將某些類型的課程發(fā)送到mongodb 通道適配器 ,以便將響應(yīng)存儲到數(shù)據(jù)庫。
下圖更好地顯示了流程的結(jié)構(gòu):
3.彈簧配置
如簡介部分所述,整個配置是使用JavaConfig定義的。 此配置分為三個文件:基礎(chǔ)結(jié)構(gòu),Web服務(wù)和數(shù)據(jù)庫配置。 讓我們來看看:
3.1基礎(chǔ)架構(gòu)配置
該配置文件僅包含消息通道的定義。 消息傳遞端點(變壓器,過濾器等)配置有注釋。
InfrastructureConfiguration.java
@Configuration @ComponentScan("xpadro.spring.integration.endpoint") //@Component @IntegrationComponentScan("xpadro.spring.integration.gateway") //@MessagingGateway @EnableIntegration @Import({MongoDBConfiguration.class, WebServiceConfiguration.class}) public class InfrastructureConfiguration {@Bean@Description("Entry to the messaging system through the gateway.")public MessageChannel requestChannel() {return new DirectChannel();}@Bean@Description("Sends request messages to the web service outbound gateway")public MessageChannel invocationChannel() {return new DirectChannel();}@Bean@Description("Sends web service responses to both the client and a database")public MessageChannel responseChannel() {return new PublishSubscribeChannel();}@Bean@Description("Stores non filtered messages to the database")public MessageChannel storeChannel() {return new DirectChannel();} }@ComponentScan注釋搜索@Component注釋的類,它們是我們定義的消息傳遞終結(jié)點; 過濾器,變壓器和服務(wù)激活器。
@IntegrationComponentScan批注搜索特定的集成批注。 在我們的示例中,它將掃描用@MessagingGateway注釋的入口網(wǎng)關(guān)。
@EnableIntegration批注啟用集成配置。 例如,方法級別的注釋,例如@Transformer或@Filter。
3.2 Web服務(wù)配置
此配置文件配置Web服務(wù)出站網(wǎng)關(guān)及其必需的編組器。
WebServiceConfiguration.java
@Configuration public class WebServiceConfiguration {@Bean@ServiceActivator(inputChannel = "invocationChannel")public MessageHandler wsOutboundGateway() {MarshallingWebServiceOutboundGateway gw = new MarshallingWebServiceOutboundGateway("http://localhost:8080/spring-ws-courses/courses", jaxb2Marshaller());gw.setOutputChannelName("responseChannel");return gw;}@Beanpublic Jaxb2Marshaller jaxb2Marshaller() {Jaxb2Marshaller marshaller = new Jaxb2Marshaller();marshaller.setContextPath("xpadro.spring.integration.ws.types");return marshaller;} }網(wǎng)關(guān)允許我們定義其輸出通道,但不能定義輸入通道。 我們需要使用@ServiceActivator注釋適配器,以便將其訂閱到調(diào)用通道,并避免必須在消息通道Bean定義中自動裝配適配器。
3.3數(shù)據(jù)庫配置
該配置文件定義了設(shè)置mongoDB所需的所有必需bean。 它還定義了mongoDB出站通道適配器。
MongoDBConfiguration.java
@Configuration public class MongoDBConfiguration {@Beanpublic MongoDbFactory mongoDbFactory() throws Exception {return new SimpleMongoDbFactory(new MongoClient(), "si4Db");}@Bean@ServiceActivator(inputChannel = "storeChannel")public MessageHandler mongodbAdapter() throws Exception {MongoDbStoringMessageHandler adapter = new MongoDbStoringMessageHandler(mongoDbFactory());adapter.setCollectionNameExpression(new LiteralExpression("courses"));return adapter;} }像Web服務(wù)網(wǎng)關(guān)一樣,我們無法將輸入通道設(shè)置為適配器。 我還通過在@ServiceActivator批注中指定輸入通道來完成此操作。
4.端點的細節(jié)
流的第一個端點是集成網(wǎng)關(guān),它將把參數(shù)(courseId)放入消息的有效負載中并將其發(fā)送到請求通道。
@MessagingGateway(name = "entryGateway", defaultRequestChannel = "requestChannel") public interface CourseService {public String findCourse(String courseId); }包含課程ID的消息將到達轉(zhuǎn)換器。 該端點將構(gòu)建Web服務(wù)期望的請求對象:
@Component public class CourseRequestBuilder {private Logger logger = LoggerFactory.getLogger(this.getClass());@Transformer(inputChannel="requestChannel", outputChannel="invocationChannel")public GetCourseRequest buildRequest(Message<String> msg) {logger.info("Building request for course [{}]", msg.getPayload());GetCourseRequest request = new GetCourseRequest();request.setCourseId(msg.getPayload());return request;} }訂閱了響應(yīng)通道,這是將發(fā)送Web服務(wù)回復的通道,有一個服務(wù)激活器將接收響應(yīng)消息并將課程名稱傳遞給客戶端:
@Component public class CourseResponseHandler {private Logger logger = LoggerFactory.getLogger(this.getClass());@ServiceActivator(inputChannel="responseChannel")public String getResponse(Message<GetCourseResponse> msg) {GetCourseResponse course = msg.getPayload();logger.info("Course with ID [{}] received: {}", course.getCourseId(), course.getName());return course.getName();} }同樣需要訂閱響應(yīng)通道的過濾器,將根據(jù)其類型決定是否將課程存儲到數(shù)據(jù)庫:
@Component public class StoredCoursesFilter {private Logger logger = LoggerFactory.getLogger(this.getClass());@Filter(inputChannel="responseChannel", outputChannel="storeChannel")public boolean filterCourse(Message<GetCourseResponse> msg) {if (!msg.getPayload().getCourseId().startsWith("BC-")) {logger.info("Course [{}] filtered. Not a BF course", msg.getPayload().getCourseId());return false;}logger.info("Course [{}] validated. Storing to database", msg.getPayload().getCourseId());return true;} }5.測試整個流程
以下客戶端將發(fā)送兩個請求; BC類型的課程請求將被存儲到數(shù)據(jù)庫中,而DF類型的課程將被最終過濾:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes={InfrastructureConfiguration.class}) public class TestApp {@AutowiredCourseService service;@Testpublic void testFlow() {String courseName = service.findCourse("BC-45");assertNotNull(courseName);assertEquals("Introduction to Java", courseName);courseName = service.findCourse("DF-21");assertNotNull(courseName);assertEquals("Functional Programming Principles in Scala", courseName);} }這將導致以下控制臺輸出:
CourseRequestBuilder|Building request for course [BC-45]CourseResponseHandler|Course with ID [BC-45] received: Introduction to JavaStoredCoursesFilter|Course [BC-45] validated. Storing to databaseCourseRequestBuilder|Building request for course [DF-21]CourseResponseHandler|Course with ID [DF-21] received: Functional Programming Principles in ScalaStoredCoursesFilter|Course [DF-21] filtered. Not a BF course六,結(jié)論
我們已經(jīng)學習了如何在不使用XML配置的情況下設(shè)置和測試支持Spring Integration的應(yīng)用程序。 請繼續(xù)關(guān)注,因為帶有Spring Integration 擴展的 Spring Integration Java DSL即將推出!
翻譯自: https://www.javacodegeeks.com/2014/05/spring-integration-4-0-a-complete-xml-free-example.html
總結(jié)
以上是生活随笔為你收集整理的Spring Integration 4.0:完整的无XML示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring / Hibernate使用
- 下一篇: 能的部首怎么读 能的部首读音