Apache Camel 超时同步路由

编程入门 行业动态 更新时间:2024-10-27 20:27:07
本文介绍了Apache Camel 超时同步路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试使用 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");
    }

}
}

这篇关于Apache Camel 超时同步路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-19 22:48:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/971502.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   Apache   Camel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!