Spring Integration執行個體程式碼分析之basic–http

來源:互聯網
上載者:User

從spring官方網站下載Spring Integration的例子代碼,裡麵包含了很多個分好類的例子

:https://github.com/SpringSource/spring-integration-samples

開啟basic檔案夾,裡面有一個http的例子

1.匯入項目

我們可以在eclipse裡進行調試,由於這些例子都是用maven構建的,最好先給eclipse安裝maven外掛程式,以及maven的wtp外掛程式(用於WEB開發)

安裝方式:eclipse-->help-->eclipemarketplace 搜尋maven

安裝前兩個就行了

之後匯入http這個例子的代碼,eclipse-->import-->existing maven projects,

選擇http檔案夾(包含pom.xml的檔案夾都可以匯入)即可匯入此項目,maven會自動去下載所需的依賴包,目錄結構如:

2.程式碼分析伺服器端的代碼

首先,從目錄可見,這是一個WEB項目,可以部署到WEB容器中,我們先看伺服器端的代碼

分析一下web.xml檔案,

web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>multipart-http</display-name>  <servlet>    <servlet-name>Multipart</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>/WEB-INF/servlet-config.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>Multipart</servlet-name>    <url-pattern>/*</url-pattern>  </servlet-mapping></web-app>

其中配置了一個servlet,名字叫Multipart,配置的類為DispatcherServlet,用過SPRING MVC的都比較熟悉這個配置,它就是SPRING展示層的控制器。

其contextConfigLocation配置的是/WEB-INF/servlet-config.xml

我們再看一下servlet-config.xml檔案

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsdhttp://www.springframework.org/schema/integration/file http://www.springframework.org/schema/integration/file/spring-integration-file.xsdhttp://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd"xmlns:int="http://www.springframework.org/schema/integration"xmlns:int-file="http://www.springframework.org/schema/integration/file"xmlns:int-http="http://www.springframework.org/schema/integration/http"xmlns:int-mail="http://www.springframework.org/schema/integration/mail"><int-http:inbound-gateway request-channel="receiveChannel"                          name="/receiveGateway"                          supported-methods="POST,GET"/>                          <int:channel id="receiveChannel"/><int:service-activator input-channel="receiveChannel" expression="payload + ' from the other side'"/></beans>

配置了一個int-http:inbound-gateway,channel和一個service-activator,inbound-gateway用來接受請求,關聯名稱/receiveGateway,接受POST GET請求,並串連到一個通道,為receiveChannel,通道關聯到一個service-activator,運算式為payload + from the other side,其中payload為從用戶端接受的資訊,添加一些資訊之後返回去。

伺服器端就是這麼簡單的內容,用spring的eclipse外掛程式開啟這個檔案,可以看到圖示:

我們可以將伺服器端運行起來,選擇pom右鍵-->run as-->maven build

在goal輸入jetty:run,確定即可。

輸出資訊如下:

[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< maven-jetty-plugin:6.1.10:run (default-cli) @ http <<<
[WARNING] The artifact org.apache.commons:commons-io:jar:1.3.2 has been relocated to commons-io:commons-io:jar:1.3.2
[INFO]
[INFO] --- maven-jetty-plugin:6.1.10:run (default-cli) @ http ---
[INFO] Configuring Jetty for project: Samples (Basic) - HTTP Demo
[INFO] Webapp source directory = /media/g_windows/ubuntudata/code/SpringSource-spring-integration-samples-84aefe6/basic/http/src/main/webapp
[INFO] web.xml file = /media/g_windows/ubuntudata/code/SpringSource-spring-integration-samples-84aefe6/basic/http/src/main/webapp/WEB-INF/web.xml
[INFO] Classes = /media/g_windows/ubuntudata/code/SpringSource-spring-integration-samples-84aefe6/basic/http/target/classes
2012-10-25 15:15:37.729::INFO: Logging to STDERR via org.mortbay.log.StdErrLog
[INFO] Context path = /http
[INFO] Tmp directory = determined at runtime
[INFO] Web defaults = org/mortbay/jetty/webapp/webdefault.xml
[INFO] Web overrides = none
[INFO] Webapp directory = /media/g_windows/ubuntudata/code/SpringSource-spring-integration-samples-84aefe6/basic/http/src/main/webapp
[INFO] Starting jetty 6.1.10 ...
2012-10-25 15:15:37.823::INFO: jetty-6.1.10
2012-10-25 15:15:37.201::INFO: No Transaction manager found - if your webapp requires one, please configure one.
2012-10-25 15:15:38.179:/http:INFO: Initializing Spring FrameworkServlet 'Multipart'
15:15:38.803 INFO [main][org.springframework.web.servlet.DispatcherServlet] FrameworkServlet 'Multipart': initialization started
15:15:38.862 INFO [main][org.springframework.web.context.support.XmlWebApplicationContext] Refreshing WebApplicationContext for namespace 'Multipart-servlet': startup date [Thu Oct 25 15:15:38 CST 2012]; root of context hierarchy
15:15:38.927 INFO [main][org.springframework.beans.factory.xml.XmlBeanDefinitionReader] Loading XML bean definitions from ServletContext resource [/WEB-INF/servlet-config.xml]
15:15:39.712 INFO [main][org.springframework.integration.config.xml.DefaultConfiguringBeanFactoryPostProcessor] No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
15:15:39.712 INFO [main][org.springframework.integration.config.xml.DefaultConfiguringBeanFactoryPostProcessor] No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
15:15:39.734 INFO [main][org.springframework.beans.factory.support.DefaultListableBeanFactory] Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@66b4c2e4: defining beans [org.springframework.integration.internalDefaultConfiguringBeanFactoryPostProcessor,/receiveGateway,receiveChannel,org.springframework.integration.config.ServiceActivatorFactoryBean#0,org.springframework.integration.config.ConsumerEndpointFactoryBean#0,nullChannel,errorChannel,_org.springframework.integration.errorLogger,taskScheduler,org.springframework.integration.config.IdGeneratorConfigurer#0];
root of factory hierarchy
15:15:40.455 INFO [main][org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler] Initializing ExecutorService 'taskScheduler'
15:15:40.461 INFO [main][org.springframework.context.support.DefaultLifecycleProcessor] Starting beans in phase -2147483648
15:15:40.462 INFO [main][org.springframework.integration.endpoint.EventDrivenConsumer] Adding {service-activator} as a subscriber to the 'receiveChannel' channel
15:15:40.462 INFO [main][org.springframework.integration.channel.DirectChannel] Channel 'receiveChannel' has 1 subscriber(s).
15:15:40.462 INFO [main][org.springframework.integration.endpoint.EventDrivenConsumer] started org.springframework.integration.config.ConsumerEndpointFactoryBean#0
15:15:40.462 INFO [main][org.springframework.integration.endpoint.EventDrivenConsumer] Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
15:15:40.462 INFO [main][org.springframework.integration.channel.PublishSubscribeChannel] Channel 'errorChannel' has 1 subscriber(s).
15:15:40.462 INFO [main][org.springframework.integration.endpoint.EventDrivenConsumer] started _org.springframework.integration.errorLogger
15:15:40.462 INFO [main][org.springframework.context.support.DefaultLifecycleProcessor] Starting beans in phase 0
15:15:40.463 INFO [main][org.springframework.integration.http.inbound.HttpRequestHandlingMessagingGateway] started /receiveGateway
15:15:40.500 INFO [main][org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping] Mapped URL path [/receiveGateway] onto handler '/receiveGateway'
15:15:40.766 INFO [main][org.springframework.web.servlet.DispatcherServlet] FrameworkServlet 'Multipart': initialization completed in 1962 ms
2012-10-25 15:15:40.169::INFO: Started SelectChannelConnector@0.0.0.0:8080[INFO] Started Jetty Server

用戶端代碼看HttpClientDemo.java
public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("/META-INF/spring/integration/http-outbound-config.xml");RequestGateway requestGateway = context.getBean("requestGateway", RequestGateway.class);String reply = requestGateway.echo("Hello");  logger.info("Replied with: " + reply);}

其中一個main函數,裡面建立一個spring 的context,使用設定檔為META-INF/spring/integration/http-outbound-config.xml

建立一個requestGateway,調用它的一個echo方法,然後得到結果,並輸出,也非常簡單。下面我們看一下RequestGateway.java
package org.springframework.integration.samples.http;/** * @author Oleg Zhurakousky * */public interface RequestGateway {public String echo(String request);}

這是一個介面,只有一個echo的方法聲明,其他什麼也沒有了,那麼調用這個方法的時候資訊發哪了?只能看看/http-outbound-config.xml配置了

<int:gateway id="requestGateway"              service-interface="org.springframework.integration.samples.http.RequestGateway"             default-request-channel="requestChannel"/><int:channel id="requestChannel"/><int-http:outbound-gateway request-channel="requestChannel"            url="http://localhost:8080/http/receiveGateway"           http-method="POST"           expected-response-type="java.lang.String"/>

配置了一個gateway,關聯上RequestGateway,並關聯一個通道requestChannel,將資訊關聯到一個outbound-gateway,將資訊以POST形式發送到http://localhost:8080/http/receiveGateway地址,正好服務端就可以接受了。右鍵run as -->java application,就可以運行了。

可以從輸出資訊中查看到結果。

15:17:07.013 INFO [main][org.springframework.context.support.ClassPathXmlApplicationContext] Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@25a268f2: startup date [Thu Oct 25 15:17:06 CST 2012]; root of context hierarchy
15:17:07.097 INFO [main][org.springframework.beans.factory.xml.XmlBeanDefinitionReader] Loading XML bean definitions from class path resource [META-INF/spring/integration/http-outbound-config.xml]
15:17:07.700 INFO [main][org.springframework.integration.config.xml.DefaultConfiguringBeanFactoryPostProcessor] No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
15:17:07.700 INFO [main][org.springframework.integration.config.xml.DefaultConfiguringBeanFactoryPostProcessor] No bean named 'taskScheduler' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.
15:17:07.715 INFO [main][org.springframework.beans.factory.support.DefaultListableBeanFactory] Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7fee6f88: defining beans [org.springframework.integration.internalDefaultConfiguringBeanFactoryPostProcessor,requestGateway,requestChannel,org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler#0,org.springframework.integration.config.ConsumerEndpointFactoryBean#0,nullChannel,errorChannel,_org.springframework.integration.errorLogger,taskScheduler,org.springframework.integration.config.IdGeneratorConfigurer#0];
root of factory hierarchy
15:17:07.934 INFO [main][org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler] Initializing ExecutorService 'taskScheduler'
15:17:07.988 INFO [main][org.springframework.integration.gateway.GatewayProxyFactoryBean$MethodInvocationGateway] started requestGateway
15:17:07.988 INFO [main][org.springframework.integration.gateway.GatewayProxyFactoryBean] started requestGateway
15:17:08.419 INFO [main][org.springframework.context.support.DefaultLifecycleProcessor] Starting beans in phase -2147483648
15:17:08.419 INFO [main][org.springframework.integration.endpoint.EventDrivenConsumer] Adding {message-handler} as a subscriber to the 'requestChannel' channel
15:17:08.419 INFO [main][org.springframework.integration.channel.DirectChannel] Channel 'requestChannel' has 1 subscriber(s).
15:17:08.420 INFO [main][org.springframework.integration.endpoint.EventDrivenConsumer] started org.springframework.integration.config.ConsumerEndpointFactoryBean#0
15:17:08.420 INFO [main][org.springframework.integration.endpoint.EventDrivenConsumer] Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
15:17:08.420 INFO [main][org.springframework.integration.channel.PublishSubscribeChannel] Channel 'errorChannel' has 1 subscriber(s).
15:17:08.420 INFO [main][org.springframework.integration.endpoint.EventDrivenConsumer] started _org.springframework.integration.errorLogger
15:17:08.420 INFO [main][org.springframework.context.support.DefaultLifecycleProcessor] Starting beans in phase 0
15:17:08.799 INFO [main][org.springframework.integration.samples.http.HttpClientDemo] Replied with: Hello from the other side

總結伺服器端組件如下:http inbound gateway 就是用來通過HTTP擷取資訊的,而service-activator通常是處理資訊的服務。用戶端組件關係:outboundgateway則是用於向外發送資料,通過這個例子可以很好的理解這兩個gateway 的作用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.