我正在尝试使用Apache构建一个带有超时的同步路由,但是我在框架中找不到任何解决它的方法。所以我决定为我建立一个过程。
public class TimeOutProcessor implements Processor {
private String route;
private Integer timeout;
public TimeOutProcessor(String route, Integer timeout) {
this.route = route;
this.timeout = timeout;
}
@Override
public void process(Exchange exchange) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Exchange> future = executor.submit(new Callable<Exchange>() {
public Exchange call() {
// Check for field rating
ProducerTemplate producerTemplate = exchange.getFromEndpoint().getCamelContext().createProducerTemplate();
return producerTemplate.send(route, exchange);
}
});
try {
exchange.getIn().setBody(future.get(
timeout,
TimeUnit.SECONDS));
} catch (TimeoutException e) {
throw new TimeoutException("a timeout problem occurred");
}
executor.shutdownNow();
}
我把这个过程叫做:
.process(new TimeOutProcessor("direct:myRoute",
Integer.valueOf(this.getContext().resolvePropertyPlaceholders("{{timeout}}")))
我想知道我的方式是否是推荐的方式,如果不是,什么是构建带有超时的同步路由的最佳方法?
发布于 2018-03-26 13:26:52
我要感谢那些回答我的人。
这是我的最后代码:
public class TimeOutProcessor implements Processor {
private String route;
private Integer timeout;
public TimeOutProcessor(String route, Integer timeout) {
this.route = route;
this.timeout = timeout;
}
@Override
public void process(Exchange exchange) throws Exception {
Future<Exchange> future = null;
ProducerTemplate producerTemplate = exchange.getFromEndpoint().getCamelContext().createProducerTemplate();
try {
future = producerTemplate.asyncSend(route, exchange);
exchange.getIn().setBody(future.get(
timeout,
TimeUnit.SECONDS));
producerTemplate.stop();
future.cancel(true);
} catch (TimeoutException e) {
producerTemplate.stop();
future.cancel(true);
throw new TimeoutException("a timeout problem occurred");
}
}
}
https://stackoverflow.com/questions/49308074
复制相似问题