如何在 ModelCamelContext 中设置自定义跟踪器?

How do I set custom tracer in ModelCamelContext?

我正在使用 camel 3.14.0 实现简单的 camel 应用程序。

我开始使用 modelcamelcontext。 但是在设置自定义跟踪器时出现以下异常。

2022-04-29 17:04:18.474  INFO 10264 --- [           main] target.atom.engine.EngineApplication     : Started EngineApplication in 14.158 seconds (JVM running for 16.177)
2022-04-29 17:04:18.540 ERROR 10264 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Cannot set tracer on a started CamelContext
    at org.apache.camel.impl.engine.AbstractCamelContext.setTracer(AbstractCamelContext.java:4601) ~[camel-base-engine-3.14.0.jar:3.14.0]
    at target.atom.common.config.TargetAtomConfig.reloadRoutes(TargetAtomConfig.java:54) ~[classes/:na]
    at target.atom.common.config.TargetAtomConfig$$FastClassBySpringCGLIB$b88810d.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.1.jar:5.3.1]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) ~[spring-aop-5.3.1.jar:5.3.1]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.1.jar:5.3.1]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.3.1.jar:5.3.1]
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:89) ~[spring-aop-5.3.1.jar:5.3.1]

如何在 modelCamelContext 中设置跟踪器?

源代码

ModelCamelContext modelCamelContext = camelContext.adapt(ModelCamelContext.class);
TraceFormatter formatter = new TraceFormatter();
modelCamelContext.setTracer(formatter.getTracer(modelCamelContext));
modelCamelContext.setTracing(true);
…

假设您使用的是 Camel Spring Boot,CamelContext 可以自定义,这要归功于 CamelContextConfiguration 类型的 bean,该 bean 用于在之前和之前添加自定义逻辑Spring Boot 和 CamelContext 完全启动后。

在您的情况下,想法是在启动前添加自定义逻辑,因此您的代码应如下所示:

@Bean
CamelContextConfiguration contextConfiguration() {
    return new CamelContextConfiguration() {
        @Override
        public void beforeApplicationStart(CamelContext context) {
            // Configure the tracer before starting up the camel context
            TraceFormatter formatter = new TraceFormatter();
            context.setTracer(formatter.getTracer(modelCamelContext));
            context.setTracing(true);
        }

        @Override
        public void afterApplicationStart(CamelContext camelContext) {
            // Nothing to do
        }
    };
}