如何通过CamelContext手动启动autoStartup=false的Camel路由?
问题
配置了以下Camel路由并设置autoStartup=false,尝试通过CamelContext手动启动但失败,控制台日志显示路由被跳过:
路由代码
@Component @ConfigurationProperties() public class S3IntegratorRoute extends RouteBuilder { @Value("${base.url}") private String url; @Value("#{${queryParams}}") private Map<String, String> query; @Autowired @Qualifier("jsonConversionProcessor") private Processor jsonProcessor; @Override public void configure() throws Exception { String queryParams = Util.buildQueryParams(query); from("timer:mytimer?repeatCount=1") .routeId("manualRestart").autoStartup(false) .setHeader(Exchange.HTTP_QUERY, simple(queryParams)) .to(url).process(jsonProcessor); } }
主类启动代码
@SpringBootApplication //@EnableDiscoveryClient public class CollibraApiApplication { public static void main(String[] args) throws Exception { ApplicationContext ctx = SpringApplication.run(CollibraApiApplication.class, args); S3IntegratorRoute s3IntegratorRoute = ctx.getBean(S3IntegratorRoute.class); ExtendedCamelContext camelContext = ctx.getBean(ExtendedCamelContext.class); camelContext.addRoutes(s3IntegratorRoute); camelContext.start(); } }
控制台日志
o.a.c.impl.engine.AbstractCamelContext : Skipping starting of route manualRestart as it's configured with autoStartup=false 2023-03-30 14:41:50.451 [] INFO 25808 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Total 1 routes, of which 0 are started 2023-03-30 14:41:50.453 [] INFO 25808 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Apache Camel 3.3.0 (CamelContext: camel-1) started in 0.030 seconds
解决方案
问题核心是重复添加路由且未主动触发指定路由启动。Spring Boot会自动将RouteBuilder类型Bean中的路由加载到CamelContext中,无需手动调用addRoutes,直接启动已注册的路由即可:
修改后主类代码
@SpringBootApplication public class CollibraApiApplication { public static void main(String[] args) throws Exception { ApplicationContext ctx = SpringApplication.run(CollibraApiApplication.class, args); CamelContext camelContext = ctx.getBean(CamelContext.class); // 通过路由ID启动目标路由 camelContext.startRoute("manualRestart"); } }
补充说明
- 路由已由Spring自动注册到
CamelContext,仅处于未激活状态,调用startRoute传入路由ID即可启动 - 若需延迟或条件启动,可在事件触发、接口调用等时机执行
startRoute方法 - 如需停止路由,可使用
camelContext.stopRoute("manualRestart")
内容的提问来源于stack exchange,提问作者Ashu Jain
相关产品推荐
相关产品推荐

