我正在 trwing 使用 Apache Camel 构造一个带有超时的同步路由,但我在框架中找不到任何可以解析它的内容。
所以我决定建立一个为我制作的流程。
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}}")))
我想知道我的方法是否是推荐的方法,如果不是,构建超时同步路由的最佳方法是什么?
我要感谢那些回答我的人。
这是我的最终代码:
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");
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)