骆驼递归调用

时间:2020-02-04 10:33:52

标签: apache-camel

我有一个使用Camel的项目,并且我的路线对其进行了递归调用,以实现逻辑“在返回数据集时调用存储过程”:

<route id="trxnReader">
    <from uri="direct:query"/>

    <to uri="sql-stored:classpath:sql/getTrxnsProcedure.sql?dataSource=myDataSource"
        id="storedprocGetTrxns"/>

    <choice>
        <when>
            <simple>${body} != null</simple>

            <split>
                <simple>${body.transactions}</simple>
                <filter>
                    <method ref="trnxFilter" method="filter"/>
                    <to uri="direct:processTrxn"/>
                </filter>
            </split>

            <to uri="direct:query"/>
        </when>
        <otherwise>
            <log id="failUploadInfo" message="Transactions don't exist" loggingLevel="INFO"/>
        </otherwise>
    </choice>
</route>

此代码的问题是,如果我的存储过程在很长一段时间内不断返回某些内容而不允许退出递归,则会得到java.lang.StackOverflowError。我需要类似循环的东西。用Camel实现这种逻辑的最佳方法是什么?我正在使用骆驼2.15.3。

1 个答案:

答案 0 :(得分:0)

我找到了一种解决方法,其中包含自定义bean和循环退出条件(isLoopDone属性)

public class LoopBean {

    @Handler
    public void loop(@ExchangeProperty("loopEndpoint") String endpoint, Exchange exchange) {
        ProducerTemplate producerTemplate = exchange.getContext().createProducerTemplate();
        boolean isLoopDone = false;
        Exchange currentExchange = exchange;

        do {
            currentExchange = producerTemplate.send(endpoint, currentExchange);
            Object isLoopDoneProperty = currentExchange.getProperty("isLoopDone");
            if (isLoopDoneProperty != null) {
                isLoopDone = (boolean) isLoopDoneProperty;
            }
        }
        while (!isLoopDone);
    }
}
<route id="trxnReader">
    <from uri="direct:query"/>
    <setProperty propertyName="loopEndpoint">
        <simple>direct:callStoredProcWhileItHasTransactions</simple>
    </setProperty>

    <bean ref="loopBean"/>
</route>

<route id="storedProcCallingLoop">
    <from uri="direct:callStoredProcWhileItHasTransactions"/>

    <to uri="sql-stored:classpath:sql/getTrxnsProcedure.sql?dataSource=myDataSource"
        id="storedprocGetTrxns"/>

    <choice>
        <when>
            <simple>${body} != null</simple>

            <split>
                <simple>${body.transactions}</simple>
                <filter>
                    <method ref="trnxFilter" method="filter"/>
                    <to uri="direct:processTrxn"/>
                </filter>
            </split>
        </when>
        <otherwise>
            <log id="failUploadInfo" message="Transactions don't exist" loggingLevel="INFO"/>
            <setProperty propertyName="isLoopDone">
                <simple resultType="java.lang.Boolean">true</simple>
            </setProperty>
        </otherwise>
    </choice>
</route>