如果您想用Spring Integration编写一个流程来轮询HTTP端点并从http端点收集一些内容以进行进一步处理,那有点不直观。

Spring Integration提供了几种与HTTP端点集成的方式-

  1. Http出站适配器–将消息发送到http端点
  2. Http出站网关–将消息发送到http端点并收集响应作为消息

我第一个轮询http端点的本能是使用Http Inbound通道适配器,我做出的错误假设是适配器将负责从端点获取信息-Http Inbound Gateway实际所做的是公开Http端点等待请求到来! ,这就是为什么我首先说,轮询URL并从中收集内容对我来说有点不直观,我实际上必须使用Http Outbound网关

在澄清了这一点之后,请考虑一个示例,在该示例中,我要轮询此URL上可用的USGS地震信息提要-http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour

这是我的示例http Outbound组件的样子:

<int:channel id='quakeinfo.channel'>
  <int:queue capacity='10'/>
 </int:channel>

 <int:channel id='quakeinfotrigger.channel'></int:channel> 

 <int-http:outbound-gateway id='quakerHttpGateway'
     request-channel='quakeinfotrigger.channel'
     url='http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour'
     http-method='GET'
     expected-response-type='java.lang.String'
     charset='UTF-8'
     reply-timeout='5000'
     reply-channel='quakeinfo.channel'>     
 </int-http:outbound-gateway>

在这里,http出站网关等待消息进入quakeinfotrigger通道,将GET请求发送到'http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour'网址,然后放置响应json字符串进入“ quakeinfo.channel”通道

测试这很容易:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration('httpgateway.xml')
public class TestHttpOutboundGateway {

 @Autowired @Qualifier('quakeinfo.channel') PollableChannel quakeinfoChannel;
 @Autowired @Qualifier('quakeinfotrigger.channel') MessageChannel quakeinfoTriggerChannel;

 @Test
 public void testHttpOutbound() {
  quakeinfoTriggerChannel.send(MessageBuilder.withPayload('').build());
  Message<?> message = quakeinfoChannel.receive();
  assertThat(message.getPayload(), is(notNullValue()));
 }

}

我在这里所做的是获取对触发出站网关向http端点发送消息的通道的引用,并获取对放置来自http端点的响应的另一个通道的引用。 我通过在触发器通道中放置一个空虚消息来触发测试流程,然后等待消息在响应通道中可用并在内容中声明。

这样做很干净,但是我的初衷是编写一个轮询器,该轮询器每分钟左右触发一次此端点的轮询,为此,我要做的实际上是每分钟将一个伪消息放入“ quakeinfotrigger.channel”通道中使用Spring Integration的“ poller”和一些Spring Expression语言可以轻松实现:

<int:inbound-channel-adapter channel='quakeinfotrigger.channel' expression=''''>
 <int:poller fixed-delay='60000'></int:poller>
</int:inbound-channel-adapter>

在这里,我有一个与轮询器相连的Spring inbound-channel-adapter触发器,该轮询器每分钟都会触发一条空消息。

所有这些看起来有些令人费解,但效果很好–这是一个具有有效代码的要点

相关链接

  1. 基于我在Spring论坛上提出的一个问题http://forum.springsource.org/showthread.php?130711-Need-help-with-polling-to-a-json-based-HTTP-service


参考: all和其他博客中使用 JCG合作伙伴 Biju Kunjummen的Spring Integration轮询http端点 。

翻译自: https://www.javacodegeeks.com/2012/11/polling-an-http-end-point-using-spring-integration.html

更多推荐