Apache Camel超时同步路由
问题描述:
我正试图使用Apache Camel构建具有超时的同步路由,但是在解决该问题的框架中我找不到任何东西. 因此,我决定为我建立一个流程.
I was trwing to construct a synchronous route with timeout using Apache Camel, and I couldn't find anything in the framework with resolve it. So I decided to build a process with make it for me.
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}}")))
我想知道我的方法是否是推荐的方法,如果不是,建立超时的同步路由的最佳方法是什么?
I wanna know if my way is the recomended way to do it, if it is not, what is the best way for build a synchronous route with timeout?
答
我要感谢回答我的人们.
I want to thanks the people who answer me.
这是我的最终代码:
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");
}
}
}