如果您想用Spring Integration編寫一個流程來輪詢HTTP端點并從http端點收集一些內容以進行進一步處理,那有點不直觀。
Spring Integration提供了幾種與HTTP端點集成的方式-
- Http出站適配器–將消息發送到http端點
- 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;@Testpublic 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觸發器,該輪詢器每分鐘都會觸發一條空消息。
所有這些看起來有些令人費解,但效果很好–這是一個具有有效代碼的要點
相關鏈接
- 基于我在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