Search code examples
apache-camelspring-camel

Apache Camel timeout synchronous route


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

And I call this process this way:

.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?


Solution

  • I want to thanks the people who answer me.

    That is my final code:

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