0

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

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

我已经尝试过定义数据源的蓝图版本,但也无法让它运行。

这是以正确的方式设置的吗?我可能缺少依赖项还是我指定了错误的驱动程序?

4

1 回答 1

1

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

在 CamelTestSupport 的 JDSL 中,上下文使用 createCamelContext 方法注册,并且数据源被添加到那里的上下文中。

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>
于 2018-03-26T07:53:38.053 回答