【问题标题】:Camel: use datasource configured by spring-bootCamel:使用 spring-boot 配置的数据源
【发布时间】:2015-10-13 12:18:11
【问题描述】:

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

@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");
  }
}

【问题讨论】:

  • 我的不好,不需要 sqlComponent Bean。由于 CamelContext 可以访问所有 spring bean 只需在 sql 端点的末尾添加 ?dataSource=dataSource 即可按预期工作
  • 您应该将该评论作为答案发布并接受它:)

标签: jdbc spring-boot apache-camel


【解决方案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=#dataSource 的使用。 dataSource 名称指向 Spring 配置的 DataSource 对象,可以更改为另一个,从而在不同的路由中使用不同的 DataSource。

【讨论】:

    【解决方案2】:

    这里是示例/示例代码 (Java DSL)。为此我使用了

    • 弹簧靴
    • H2 嵌入式数据库
    • 骆驼

    在启动 spring-boot 时,创建表并加载数据。然后骆驼路线,运行“选择”来拉数据。

    这里是代码

    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}")
    

    full example in github

    【讨论】:

      猜你喜欢
      • 2018-06-14
      • 2016-01-17
      • 2015-01-26
      • 2021-03-16
      • 2018-03-22
      • 1970-01-01
      • 2021-06-22
      相关资源
      最近更新 更多