`
Javahuhui
  • 浏览: 78399 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

spring boot集成spring integration

阅读更多

主要使用integration的聚合器

1.pom.xml关键jar引用

 

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.integration</groupId>
	<artifactId>spring-integration-http</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.integration</groupId>
	<artifactId>spring-integration-stream</artifactId>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.51</version>
</dependency>
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.6</version>
</dependency>
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpmime</artifactId>
	<version>4.5.6</version>
</dependency>
<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-core</artifactId>
	<scope>provided</scope>
</dependency>

 2.http-inbound-config.xml配置

 

 

<?xml version="1.0" encoding="UTF-8"?>
<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"
       xmlns:context="http://www.springframework.org/schema/context" 
xmlns="http://www.springframework.org/schema/beans"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/integration 
http://www.springframework.org/schema/integration/spring-integration.xsd
		http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/integration/http 
http://www.springframework.org/schema/integration/http/spring-integration-http.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd">

	<int:channel id="echoChannel">
		<int:queue capacity="1000"/>
	</int:channel>
	<int-http:inbound-gateway request-channel="echoChannel" path="/cc/test" 
               supported-methods="POST" request-payload-type="java.lang.String">
        <int-http:cross-origin/>
    </int-http:inbound-gateway>
    <int:chain input-channel="echoChannel" output-channel="search-request-a">
		<int:poller fixed-rate="1" max-messages-per-poll="10" time-unit="SECONDS">
		</int:poller>
		<int:header-enricher>
        	<int:header name="ssmail" value="test"/>
        </int:header-enricher>
		<int-http:outbound-gateway charset="UTF-8" http-method="POST" 
                 expected-response-type="com.test.integration.splitteraggregator.CriteriaA"
		 encode-uri="true" url="{testApi}" uri-variables-expression="@testApi" 
                 reply-timeout="30000" />
	</int:chain>
	
    <bean id="serviceActivatorA" 
      class="com.test.integration.splitteraggregator.ServiceActivatorA"></bean>
	<int:service-activator input-channel="search-request-a"
		method="service" output-channel="search-reply" ref="serviceActivatorA">
	</int:service-activator>
	
	<int:channel id="echoChannel2">
		<int:queue capacity="1000"/>
	</int:channel>
	<int:logging-channel-adapter id="logger" level="INFO" log-full-message="true"/>
	<int-http:inbound-gateway request-channel="echoChannel2" path="/cc/test2" 
            supported-methods="POST" request-payload-type="java.lang.String">
        <int-http:cross-origin/>
    </int-http:inbound-gateway>
    <int:chain input-channel="echoChannel2" output-channel="search-request-b">
		<int:poller fixed-rate="1" max-messages-per-poll="10" time-unit="SECONDS">
		</int:poller>
		<int:header-enricher>
        	<int:header name="ssmail" value="test"/>
        </int:header-enricher>
		<int-http:outbound-gateway charset="UTF-8" http-method="POST" 
                    expected-response-type="byte[]"
		    encode-uri="true" url="{test2Api}" uri-variables-expression="@test2Api" 
                    reply-timeout="30000" />
	</int:chain>
	
	<!-- <int:channel id="search-request-b"/> -->
    <bean id="serviceActivatorB" 
      class="com.test.integration.splitteraggregator.ServiceActivatorB"></bean>
	<int:service-activator input-channel="search-request-b"
		method="service" output-channel="search-reply" ref="serviceActivatorB">
	</int:service-activator>
	
	<int:channel id="aggregated-reply"/>
	<int:channel id="search-reply" >
	<int:interceptors>
			<int:wire-tap channel="logger" />
		</int:interceptors>
	</int:channel>
	<int:aggregator input-channel="search-reply" method="aggregate" 
		ref="resultAggregator" output-channel="aggregated-reply"
		message-store="searchResultMessageStore"
		expire-groups-upon-completion="true"
		correlation-strategy-expression="headers['ssmail']"
        expire-groups-upon-timeout="true"
        release-strategy-expression="size() == 2" 
		send-partial-result-on-expiry="true">
	</int:aggregator>
	<int:logging-channel-adapter channel="aggregated-reply" level="INFO" 
           log-full-message="true"></int:logging-channel-adapter>

	<!-- Define a store for our search results and set up a reaper that will
		periodically expire those results. -->
	<bean id="searchResultMessageStore" 
           class="org.springframework.integration.store.SimpleMessageStore" />

	<bean id="searchResultMessageStoreReaper" 
           class="org.springframework.integration.store.MessageGroupStoreReaper">
		<property name="messageGroupStore" ref="searchResultMessageStore" />
		<property name="timeout" value="20000" />
	</bean>
	<bean id="resultAggregator" 
           class="com.test.integration.splitteraggregator.ResultAggregator" />
	
</beans>

 说明:path="/cc/test"是本地监听路径,标蓝url="{testApi}"即为实际访问路径,并返回结果到search-request-a这个通道中,再由serviceActivatorA处理结果集,最后交给search-reply聚合数据。

 

3.相关java代码

//响应信息
public class Result {
	private String title;
	private String content;
}

public class CriteriaA {
	private Boolean success;//根据系统响应属性不同而定义
	private String code;
        private String error;
	private Result result;
}

public class CriteriaB {
	private Integer code;//根据系统响应属性不同而定义
        private String errmsg;
	private Result result;
}

 

//响应信息处理,处理方式根据系统响应结果而定
public class ServiceActivatorA {
	public Result service(CriteriaA criteria) {
		Result result = new Result();
		if(criteria.getSuccess() && criteria.getResult!=null){
			result = criteria.getResult();
		}
		return result;
	}
}

public class ServiceActivatorB {
	public Result service(byte[] data) {
		Result result = new Result();
		try {
			String dataStr = new String(data, "UTF-8");
			CriteriaB criterib = JSON.parseObject(dataStr, CriteriaB.class);
			if(criterib.getCode()==10000 && criterib.getResult()!=null) {
				result = criterib.getResult();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}

 

//聚合结果集
public class CompositeResult extends Result {
	private Collection<Result> results = new ArrayList<Result>();
	public Collection<Result> getResults() {
		return results;
	}
}

public class ResultAggregator {
	public Result aggregate(Collection<Result> results) {
		CompositeResult result = new CompositeResult();
		result.getResults().addAll(results);
		System.out.println("result size:"+result.getResults().size());
		//具体业务处理。。。
		return result;
	}
}

 另外说明uri-variables-expression动态配置:获取bean对象返回值(该值必须为map),然后通过{xxx}这个方式获取,关键代码:

@Configuration
public class UrlConfig {
	@Value("${url.testApi}")
	private String testApi;
	@Value("${url.test2Api}")
	private String test2Api;

	@Bean(name="testApi")
	public Map<String, String> getTestApi() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("testApi", testApi);
		return map;
	}

	@Bean(name="test2Api")
	public Map<String, String> getTest2Api() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("test2Api", test2Api);
		return map;
	}
}

4.项目启动

@SpringBootApplication
@ImportResource(locations = "classpath:http-inbound-config.xml")
@EnableIntegration
public class HttpApplication {
    public static void main(String[] args) {
        SpringApplication.run(HttpApplication.class, args);
    }
}

  

5.访问,注意要保证跳转的路径(testApi,test2Api)能访问

可通过Restlet Client访问,post请求输入localhost:8080/cc/test,localhost:8080/cc/test2,若有参数就输入参数

  • 大小: 22 KB
分享到:
评论

相关推荐

    spring boot集成kafka

    压缩包中有两个集成kafka的项目,第一个是spring boot默认的集成方式kafkaTest1,第二个是springboot集成插件spring-integration-kafka来配置的

    Beginning Spring Boot 2 Applications and Microservices with the Spring Framework

    This book will help you understand what Spring Boot is, how Spring Boot helps you build Spring-based applications quickly and easily, and the inner workings of Spring Boot using easy-to-follow ...

    Spring Boot 2 Recipes: A Problem-Solution Approach

    Using a problem-solution approach, Spring Boot 2 ... Other recipes cover topics such as using and integrating Boot with Spring's enterprise services, Spring Integration, testing, monitoring and more.

    Learn Microservices with Spring Boot

    Build a microservices architecture with Spring Boot, by evolving an application from a small monolith to an event-driven architecture composed of several services. This book follows an incremental ...

    Beginning Spring Boot 2

    Spring is the most popular Java-based framework for building ... Spring Boot addresses this “Spring applications need complex configuration” problem by using its powerful autoconfiguration mechanism.

    Beginning-Spring-Boot-2.pdf

    This book will help you understand what Spring Boot is, how Spring Boot helps you build Spring-based applications quickly and easily, and the inner workings of Spring Boot using easy-to-follow ...

    spring-boot2-sleuth-integration-demo:Spring Cloud Sleuth与Spring Boot 2功能端点的集成

    spring-boot2-sleuth集成演示 Spring Cloud Sleuth与Spring Boot 2功能端点的集成。 一个演示应用程序,用于显示Spring Boot 2 WebFulx应用程序的Spring Cloud Sleuth集成。 要运行该应用程序,请使用以下命令...

    Spring Boot整合FTPClient线程池的实现示例

    主要介绍了Spring Boot整合FTPClient线程池的实现示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    Spring boot cli 2.2.2 命令行接口

    Spring Boot does not require any special tools integration, so you can use any IDE or text editor. Also, there is nothing special about a Spring Boot application, so you can run and debug a Spring ...

    SpringBootIntegration:SpringBoot集成学习项目

    感谢JetBrains提供IDEA与DataGrip软件支持 的github :link: 吉蒂 :link: 此项目依赖于公共组件LazyerStarter 先将lazyer那个项目克隆下来,再在lazyer项目下执行... git添加多远程仓库 ...#配合配套文章食用更加哦〜

    基于Java的微服务实践,单体微服务创建、Docker部署、Dubbo微服务实践等.zip

    spring-boot-integration Sping Boot多模块示例 spring-boot-dubbo Sping Boot整合Dubbo spring-boot-mybatis Spring Boot集成MyBatis,分页插件PageHelper,通用Mapper,MyBatis的关联表查询 spring-boot-security ...

    Pivotal Certified Spring Enterprise Integration Specialist Exam(Apress,2015)

    the Spring Web Services framework, RESTful services with Spring MVC, the Spring JMS module, JMS and JTA transactions with Spring, batch processing with Spring Batch and the Spring Integration ...

    介绍Spring Cloud Stream与RabbitMQ集成

    介绍Spring Cloud Stream与RabbitMQ集成的代码示例。Spring Cloud Stream是一个建立在Spring Boot和Spring Integration之上的框架,有助于创建事件驱动或消息驱动的微服务。

    Spring Boot Messaging

    Spring Boot Messaging: Messaging APIs for Enterprise and Integration Solutions by Felipe Gutierrez English | 5 Jun. 2017 | ISBN: 1484212258 | 196 Pages | PDF | 6.36 MB Build messaging applications ...

    angular2-spring, Angular 2 和 Spring Integration.zip

    angular2-spring, Angular 2 和 Spring Integration Angular 2 Spring Boot 集成这里示例演示如何使用 Angular 和 Spring Boot ( RestController ) 对分页表进行分页安装后端你将需要 Maven 3 和 Java 8前

    spring-boot-reference.pdf

    40. Spring Integration 41. Spring Session 42. Monitoring and Management over JMX 43. Testing 43.1. Test Scope Dependencies 43.2. Testing Spring Applications 43.3. Testing Spring Boot Applications 43.3...

Global site tag (gtag.js) - Google Analytics