6.6. camel-sql

SQL 组件允许您使用 JDBC 查询处理数据库。此组件和 JDBC 组件之间的区别在于,如果 SQL 查询是端点的属性,它将消息有效负载用作传递给查询的参数。

CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
    @Override
    public void configure() throws Exception {
        from("sql:select name from information_schema.users?dataSource=java:jboss/datasources/ExampleDS")
        .to("direct:end");
    }
});
注意

上面显示的 JNDI 数据源查找仅在配置 DefaultCamelContext 时正常工作。请参阅以下适用于 CdiCamelContextSpringCamelContext 示例。

camel-cdi 组件一起使用时,Java EE 注解可以为 Camel 提供数据源。本例使用 @Named 注释,以便 Camel 能够发现所需的数据源。

public class DatasourceProducer {
    @Resource(name = "java:jboss/datasources/ExampleDS")
    DataSource dataSource;

    @Produces
    @Named("wildFlyExampleDS")
    public DataSource getDataSource() {
        return dataSource;
    }
}

现在,可以通过 camel-sql 端点配置上的 dataSource 参数来引用数据源。

@ApplicationScoped
@ContextName("camel-sql-cdi-context")
@Startup
public class CdiRouteBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("sql:select name from information_schema.users?dataSource=wildFlyExampleDS")
        .to("direct:end");
    }
}

使用 camel-spring 时,路由配置类似如下:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">

    <jee:jndi-lookup id="wildFlyExampleDS" jndi-name="java:jboss/datasources/ExampleDS"/>

    <camelContext id="sql-spring-context" xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="sql:select name from information_schema.users?dataSource=#wildFlyExampleDS" />
            <to uri="direct:end" />
        </route>
    </camelContext>

</beans>

6.6.1. Spring JDBC XML 命名空间支持

支持以下 Spring JDBC XML 配置

jdbc:embedded-database

<jdbc:embedded-database id="datasource" type="H2">
  <jdbc:script location="db-schema.sql"/>
</jdbc:embedded-database>
注意

默认情况下,仅支持 H2 数据库,因为 JBoss EAP 具有原生支持。如果要使用其他嵌入式数据库供应商,您需要安装适当的数据库驱动程序。

jdbc:initialize-database

<jdbc:initialize-database data-source="datasource">
  <jdbc:script location="classpath:db-init.sql"/>
</jdbc:initialize-database>