本案例一共需要两个项目,一个server项目,一个client项目。
测试截屏
运行client项目的httpdemo main方法,可以收到server端返回的字符串,并且打印在控制台,就表示项目运行成功。
server项目
server只是用来测试用的,提供一个可以通过http请求返回字符串的接口就可以,不涉及到integration的知识。
本次测试,我简单的用springboot 写了一个接口。
-
源码地址
https://gitee.com/bseaworkspace/study_java_web/tree/master/springbootbasic -
代码结构
-
测试
client项目
采用了spring integration getway的方式,从http的接口中获取返回数据。
-
源码地址
https://gitee.com/bseaworkspace/study_java_web/tree/master/springintegrationHttp -
代码结构
-
测试
运行client项目的httpdemo main方法,可以收到server端返回的字符串,并且打印在控制台,就表示项目运行成功。
源码解析
- Gateway
gateway有一个service-interface的属性,这个属性指向一个interface (自定义的RequestGateway),这样,当用户调用该接口的方法的时候,spring integration就会自动地帮我们新建一个message,并提交到default-request -channel指定地channel上。
package com.xsz;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Oleg Zhurakousky
* @author Gary Russell
*
*/
public class HttpClientDemo {
private static Log logger = LogFactory.getLog(HttpClientDemo.class);
public static void main(String[] args) {
ConfigurableApplicationContext 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("\n\n++++++++++++ Replied with: " + reply + " ++++++++++++\n");
context.close();
}
}
springintegrationHttp/src/main/resources/META-INF/spring/integration/http-outbound-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"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-http="http://www.springframework.org/schema/integration/http"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http https://www.springframework.org/schema/integration/http/spring-integration-http.xsd">
<int:gateway id="requestGateway"
service-interface="com.xsz.RequestGateway"
default-request-channel="requestChannel"/>
<int:channel id="requestChannel"/>
<int-http:outbound-gateway request-channel="requestChannel"
url="http://localhost:9001/springboot1/server"
http-method="POST"
expected-response-type="java.lang.String"/>
</beans>
Spring Integration HTTP Support
官方文档地址:
https://docs.spring.io/spring-integration/docs/current/reference/html/http.html#inbound
- 本项目往外发送HTTP请求的组件
需要预先设置外部http api返回的数据类型, 外面api的地址,请求方式等等
- 本项目接收外部HTTP请求的组件
Spring Integration系列
- 《1》Hello World项目
https://blog.csdn.net/h356363/article/details/112076788 - 《2》 http项目
https://blog.csdn.net/h356363/article/details/112120991