Apache camel - 我使用 Spring XML 来定义我的 Camel 上下文。是否可以在运行时在 Java 中获取相同的 camelcontext 对象?

Apache camel - I use Spring XML to define my Camel Context. Is it possible to get the same camelcontext object in Java at runtime?

我使用 Spring XML 来定义我的 Camel 上下文。是否可以在运行时在 Java 中获取相同的 camelcontext 对象?我需要这个对象来添加更多数据并将其发送到现有路线。我无法在 XML 中执行此操作并且需要该对象,因为我将侦听错误并且必须在触发事件侦听器时采取行动。

<?xml version="1.0" encoding="UTF-8"?>
<!-- Configures the Camel Context-->

   <camelContext id="ovcOutboundCamelContext" 
                 errorHandlerRef="deadLetterErrorHandler" 
                 xmlns="http://camel.apache.org/schema/spring" 
                 useMDCLogging="true">

       <route id="processAuctionMessageRoute">
            <from uri="direct:processAuctionMessage"/>
            <to uri="bean:CustomerService?method=processAuctionMessage"/>
            <to uri="direct:splitMessage"/>
        </route>

        <route id="splitMessagesRoute">
        <from uri="direct:splitMessage"/>
        <split parallelProcessing="true" executorServiceRef="auctionsSplitThreadPoolProfile" id="splitId">
            <simple>${body}</simple>
            <to uri="bean:CustomerService?method=transformCompanyMessageForAuction"/>
            <to uri="bean:CustomerService?method=processCompanyMessageForAuction"/>
        </split>
        <to uri="direct:end"/>           
    </route>

    <route id="endProcessor">
        <from uri="direct:end"/>
        <log loggingLevel="INFO" message="End of route ${threadName}"/>
    </route>
</camelContext>

我正在尝试使用 Java 中已经存在的路由获取此上下文,但它没有用。请帮忙。

public  void test() throws Exception {      
    CamelContext context = new DefaultCamelContext();
    context.start();
    System.out.println("context:" + context.getRoutes().size());
    context.getRoute("direct:gotoExistingProcess");     
    addRoutesToCamelContext(context);
    System.out.println("context:" + context.getRoutes().size());
    context.stop();
}

您是否考虑过从 spring 应用程序上下文中获取名为 "ovcOutboundCamelContext" 的 Bean。

尽管我认为您的问题可以更容易地解决: http://camel.apache.org/loading-routes-from-xml-files.html

在 camel 的文档中,我们有这个:

CamelContextAware If you want to be injected with the CamelContext in your POJO just implement the CamelContextAware interface; then when Spring creates your POJO the CamelContext will be injected into your POJO. Also see the Bean Integration for further injections.

您可以在 Spring 中创建一个实现 CamelContextAware 的 bean,如下所示:

    @Service
    public class RouteManager implements CamelContextAware { 

    protected CamelContext camelContext;

    public CamelContext getCamelContext() {
     return camelContext;
    }

    public void setCamelContext(CamelContext camelContext) {
     this.camelContext = camelContext;
    }
}

如果您不使用注释,您可以使用:

<bean id="RouteManager " class="myPackage.RouteManager" />

获取上下文后,您可以使用代码,但不必启动或停止上下文。