骆驼(Camel):使用由Spring Boot配置的数据源

3

我有一个项目,其中使用了spring-boot-jdbc-starter并自动为我配置了数据源。 现在我添加了camel-spring-boot到项目中,并成功地从类型为RouteBuilder的bean创建路由。 但是当我使用camel的sql组件时,它找不到数据源。是否有简单的方法将Spring配置的数据源添加到CamelContext中? 在camel项目示例中,它们使用Spring xml进行数据源配置,但我正在寻找一种使用Java配置的方法。 这是我尝试过的:

@Configuration
public class SqlRouteBuilder extends RouteBuilder {
  @Bean
  public SqlComponent sqlComponent(DataSource dataSource) {
    SqlComponent sqlComponent = new SqlComponent();
    sqlComponent.setDataSource(dataSource);
    return sqlComponent;
  }

  @Override
  public void configure() throws Exception {
    from("sql:SELECT * FROM tasks WHERE STATUS NOT LIKE 'completed'")
            .to("mock:sql");
  }
}

1
我的错,不需要sqlComponent Bean。因为所有的Spring Beans都可以通过CamelContext访问。只需在sql端点末尾添加?dataSource=dataSource即可按预期工作。 - Meysam
1
你应该将那个评论发布为答案并接受它 :) - Matthew Fontana
2个回答

1
我必须发布它,因为尽管答案在评论中,但您可能没有注意到,在我的情况下,这样的配置是运行该进程所必需的。 使用SQL组件应该像这样:
         from("timer://dbQueryTimer?period=10s")
                .routeId("DATABASE_QUERY_TIMER_ROUTE")
                .to("sql:SELECT * FROM event_queue?dataSource=#dataSource")
                .process(xchg -> {
                    List<Map<String, Object>> row = xchg.getIn().getBody(List.class);
                    row.stream()
                            .map((x) -> {
                                EventQueue eventQueue = new EventQueue();
                                eventQueue.setId((Long)x.get("id"));
                                eventQueue.setData((String)x.get("data"));
                                return eventQueue;
                            }).collect(Collectors.toList());
                })
                .log(LoggingLevel.INFO,"******Database query executed - body:${body}******");

注意使用?dataSource=#dataSourcedataSource名称指向由Spring配置的DataSource对象,它可以更改为另一个,并因此在不同路由中使用不同的DataSource。

0

这里是示例代码(Java DSL)。我使用了以下技术:

  • Spring Boot
  • H2嵌入式数据库
  • Camel

在启动Spring Boot时,会创建表并加载数据。然后Camel路由会运行“select”语句来获取数据。

以下是代码:

public void configure() throws Exception {

    from("timer://timer1?period=1000")
    .setBody(constant("select * from Employee"))
    .to("jdbc:dataSource")
    .split().simple("${body}")
    .log("process row ${body}")

在Github上的完整示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接