Apache Camel超时同步路由

时间:2018-03-15 19:50:55

标签: apache-camel spring-camel

我正在尝试使用Apache Camel构建一个带超时的同步路由,我无法在框架中找到解决它的任何内容。 所以我决定为我制作一个流程。

>>> s = 10
>>> '/path/to/file/{}.png'.format(s)
'/path/to/file/10.png'

我用这种方式称呼这个过程:

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();
}

我想知道我的方式是否是推荐的方式,如果不是,那么构建具有超时的同步路由的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

我要感谢回答我的人。

这是我的最终代码:

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");
    }

}
}