无法使用camel SQL组件

时间:2018-03-21 16:49:26

标签: java apache-camel camel-sql

尝试连接到mariDB数据库时,我总是遇到以下异常,我无法弄清楚如何正确定义dataSource。

No bean could be found in the registry for: myDataSource of type: javax.sql.DataSource

我的代码非常简单,如下所示:

protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {


        @Override
        public void configure() throws Exception {

            String url = "jdbc:mariadb://localhost:3306/testDB";

            BasicDataSource ds = new BasicDataSource();
            ds.setUsername("user");
            ds.setDriverClassName("com.mysql.jdbc.Driver");
            ds.setPassword("password");
            ds.setUrl(url);

            SimpleRegistry registry = new SimpleRegistry();
            registry.put("myDataSource", ds);
            CamelContext context = new DefaultCamelContext(registry);


            this.setContext(context);

            //poll the mySQL Database every x minutes.
            from("timer://Timer?period=6000")

            .to("sql:select * from testDB?dataSource=myDataSource");
       }
    };
}

我已经尝试过定义dataSource的Blueprint版本,但是无法运行它。

这是否以正确的方式设置? 我可能错过了一个依赖项,或者我指定了错误的驱动程序?

1 个答案:

答案 0 :(得分:1)

在查看示例后,我发现了如何解决我的问题。

在CamelTestSupport的JDSL中,使用createCamelContext方法注册上下文,并将dataSource添加到上下文中。

public class IntegrationTest extends CamelTestSupport{

@Override
public CamelContext createCamelContext() {
    String url = "jdbc:mysql://localhost:3306/";
    DataSource dataSource = setupDataSource(url);
    SimpleRegistry registry = new SimpleRegistry();
    registry.put("myDataSource", dataSource);
    CamelContext context = new DefaultCamelContext(registry);
    return context;
}

private static DataSource setupDataSource(String connectURI) {
    BasicDataSource ds = new BasicDataSource();
    ds.setUsername("username");
    ds.setPassword("password");
    ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
    ds.setUrl(connectURI);
    return ds;
}

protected RouteBuilder createRouteBuilder() {
    return new RouteBuilder() {


        @Override
        public void configure() throws Exception {

            from("timer://Timer?period=6000")
                    .to("sql:select * from testdb.testTable
                            + " ?dataSource=myDataSource" )
                    .to("mock:result");

        }
    };
}

在蓝图文件中,需要设置/配置bean,然后由SQL组件以下列方式引用:

  <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="http:localhost:3306"/>
    <property name="username" value="username"/>
    <property name="password" value="password"/>
  </bean>

 <bean id="sql" class="org.apache.camel.component.sql.SqlComponent">
    <property name="dataSource" ref="dataSource"/>
 </bean>