五次,每次要重复任务(调用外部API),直到任一满足下面的条件。如何将任务最大重复使用Apache的骆驼
- 响应代码是成功(200)
- 试过5次。
对于重复任务,我们可以在骆驼中使用loop
。不幸的是,loop
直到骆驼版本2.17才支持条件,并且我有一些限制,迫使我使用骆驼的旧版本。
我该如何解决上面使用Apache骆驼的问题?
五次,每次要重复任务(调用外部API),直到任一满足下面的条件。如何将任务最大重复使用Apache的骆驼
对于重复任务,我们可以在骆驼中使用loop
。不幸的是,loop
直到骆驼版本2.17才支持条件,并且我有一些限制,迫使我使用骆驼的旧版本。
我该如何解决上面使用Apache骆驼的问题?
您可以使用direct
像无条件跳转goto
。这里是一个例子:
from("direct:executeHttpRequest").routeId("executeHttpRequest")
.to("http4://test.com?throwExceptionOnFailure=false&httpClientConfigurerRef=#customHttpConfigurator" + ((proxySettings == null || "none".equals(proxySettings)) ? "" : "&" + proxySettings))//?httpClientConfigurerRef=#customHttpConfigurator
.log("HTTP response code: ${in.header.CamelHttpResponseCode}")
.choice()
.when(PredicateBuilder.and(header(Exchange.HTTP_RESPONSE_CODE).isNotNull(),
constant(HttpStatus.SC_OK).isEqualTo(header(Exchange.HTTP_RESPONSE_CODE))))
.log(LoggingLevel.INFO, logger, "200 is OK!")
.removeHeader(Exchange.HTTP_RESPONSE_CODE)
.removeHeader("LoopIndex")
//Something useful here
.otherwise()
.log(LoggingLevel.INFO, logger, "Repeat request, waiting ${header.DELAY} millis...")
.delay(5000)
.removeHeader(Exchange.HTTP_RESPONSE_CODE)
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
int ind = (exchange.getIn().getHeader("LoopIndex") == null ? 0 : exchange.getIn().getHeader("LoopIndex", Integer.class));
ind++;
exchange.getIn().setHeader("LoopIndex", ind);
if (ind >= repeatCount) {
throw new RuntimeCamelException("Server not response without error " + repeatCount+" time ");
}
}
})
.to("direct:executeHttpRequest")
.end();
}
看看direct:executeHttpRequest
的工作。看起来有点可怕,但它有效。
我会利用骆驼错误处理&交还 - http://camel.apache.org/redeliverypolicy.html。
您可能需要自己抛出异常,这取决于终端如何使用非200个响应访问API交易。在HTTP组件(http://camel.apache.org/http.html)的throwExceptionOnFailure
设置可能会做你想做的(虽然我怀疑它会考虑任何的2xx或3xx应答是成功的,而不是你的非常严格的200只要求)