近期项目中一直使用Spring Integration开发,所以在此记录一下。
本次主要记录使用Spring Integration 对多组数据进行aggregation的场景。
在对多组数据进行aggregation的时候,可以使用<aggregator>。
首先,模拟一下inbound data。
<int-jdbc:inbound-channel-adapter data-source="dataSource" channel="channel1" query="select * from company_t" row-mapper="companyRowMapper">
<int:poller fixed-rate="10000">
</int:poller>
</int-jdbc:inbound-channel-adapter>
<int-jdbc:inbound-channel-adapter data-source="dataSource" channel="channel2" query="select * from product_t" row-mapper="productRowMapper">
<int:poller fixed-rate="20000">
</int:poller>
</int-jdbc:inbound-channel-adapter>
使用jdbc:inbound-channel-adapter 从数据库中获取数据。假设我们想要对两组数据进行整合或者做一些相关联的行为,那么aggregator就正好适合。
<int:header-enricher input-channel="channel1" output-channel="mergeChannel">
<int:correlation-id value="data" />
</int:header-enricher>
<int:header-enricher input-channel="channel2" output-channel="mergeChannel">
<int:correlation-id value="data" />
</int:header-enricher>
对两组数据的header进行enrich,这样就可以在Java代码中获取并操作相关数据。
public Message<?> releaseData(List<Message<?>> messages) {
//todo
}
@CorrelationStrategy
public String correlateBy(@Header("correlationId") String id) {
return "data";
}
@ReleaseStrategy
public boolean release(List<Message<?>> messages) {
return messages.size() == size;
}
注意@CorrelationStrategy用来关联我们之前enrich过header的Message。
@ReleaseStrategy发布策略用来决定何时将数据push到另一端的channel。通常用size决定,例如收到n组数据,读取n个文件等等。
这里的releaseData方法做具体的数据处理。当然,需要在配置文件进行相关配置。
<int:aggregator input-channel="mergeChannel" output-channel="dataChannel"
ref="jdbcAggregator" method="releaseData">
</int:aggregator>
至此,一个简易的Spring Integration data aggregation例子就完成了。
初次记录。