如何在 Spring Boot 1.3.x 中使用默认 Tomcat 连接池在 DataSource 上设置自定义连接属性

新手上路,请多包涵

我需要设置一些特定的 Oracle JDBC 连接属性以加快批处理 INSERT s ( defaultBatchValue ) 和批量 SELECT s ( defaultRowPrefetch ) --- )。我收到了如何使用 DBCP 实现这一目标的 建议(感谢 M. Deinum),但我想:

  • 保留默认的Tomcat jdbc连接池
  • 保留 application.yml 进行配置

我正在考虑将来支持 spring.datasource.custom_connection_properties 或类似的功能请求,因此试图假装这已经成为可能。我通过在创建 DataSource 时传递相关信息来做到这一点,并像这样操纵 DataSource 的创建:

 @Bean
public DataSource dataSource() {
    DataSource ds = null;

    try {
        Field props = DataSourceBuilder.class.getDeclaredField("properties");
        props.setAccessible(true);
        DataSourceBuilder builder = DataSourceBuilder.create();
        Map<String, String> properties = (Map<String, String>) props.get(builder);

        properties.put("defaultRowPrefetch", "1000");
        properties.put("defaultBatchValue", "1000");

        ds = builder.url( "jdbc:oracle:thin:@xyz:1521:abc" ).username( "ihave" ).password( "wonttell" ).build();

        properties = (Map<String, String>) props.get(builder);

        log.debug("properties after: {}", properties);
    } ... leaving out the catches ...
    }
    log.debug("We are using this datasource: {}", ds);
    return ds;
}

在日志中,我可以看到我正在创建正确的数据源:

 2016-01-18 14:40:32.924 DEBUG 31204 --- [           main] d.a.e.a.c.config.DatabaseConfiguration   : We are using this datasource: org.apache.tomcat.jdbc.pool.DataSource@19f040ba{ConnectionPool[defaultAutoCommit=null; ...

2016-01-18 14:40:32.919 DEBUG 31204 --- [           main] d.a.e.a.c.config.DatabaseConfiguration   : properties after: {password=wonttell, driverClassName=oracle.jdbc.OracleDriver, defaultRowPrefetch=1000, defaultBatchValue=1000, url=jdbc:oracle:thin:@xyz:1521:abc, username=ihave}

执行器显示我的代码替换了数据源:

在此处输入图像描述

但是设置没有激活,我可以在分析应用程序时看到。 defaultRowPrefetch 仍然在 10 这导致我的 SELECT s 比激活 1000 时慢得多

原文由 Marged 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 566
1 个回答

设置池 连接 属性应该可以工作。这些将被传递给 JDBC 驱动程序。将此添加到 application.properties:

 spring.datasource.connectionProperties: defaultRowPrefetch=1000;defaultBatchValue=1000

编辑(一些背景信息):

另请注意,您可以通过 spring.datasource.* 配置任何 DataSource 实现特定的属性:有关更多详细信息,请参阅您正在使用的连接池实现的文档。

来源: spring-boot 文档

原文由 Cyril 发布,翻译遵循 CC BY-SA 3.0 许可协议