使用 Spring Boots application.properties 优化 JDBC 获取大小

Optimizing JDBC fetch size by use of Spring Boots application.properties

我的 Spring 基于 Boot 1.3.1 的应用程序依赖于 Oracle 11.2 数据库,我想调整 SELECT 语句结果的获取。

JdbcTemplate 提供 public void setFetchSize(int fetchSize) 来调整获取大小,对于 Oracle,驱动程序将其预设为 10

Set the fetch size for this JdbcTemplate. This is important for processing large result sets: Setting this higher than the default value will increase processing speed at the cost of memory consumption; setting this lower can avoid transferring row data that will never be read by the application. Default is -1, indicating to use the JDBC driver's default (i.e. to not pass a specific fetch size setting on the driver).

Oracle JDBC 驱动程序(我使用 ojdbc7.jar 因为它向下兼容)提供了一个 defaultRowPrefetch 参数来增加完整数据库连接的提取大小。

根据the docs,这个参数可以这样设置:

java.util.Properties info = new java.util.Properties();
info.put ("user", "scott");
info.put ("password","tiger");
info.put ("defaultRowPrefetch","15");
getConnection ("jdbc:oracle:oci8:@",info);

但我的应用程序是使用 application.yml:

配置的
datasource:
    url: jdbc:oracle:thin:@xyz:1521:abc
    username: ${name}
    password: ${password}
    driver-class-name: oracle.jdbc.driver.OracleDriver
    ...

即使我想更改该配置以使用 spring.datasource.url=jdbc:...,也无法根据 this post.

全局设置获取大小

是否有更多 "Spring Boot style" 方法,或者我是否需要手动配置每个模板?

A BeanPostProcessor 将处理 ApplicationContext 中的所有 bean,这样您就可以添加额外的配置或根据需要完全替换它。

您可以创建一个 BeanPostProcessor,将属性添加到已配置的 DataSource。下面的示例假定使用 commons-dbcp 1 或 2,如果您相应地使用不同的 DataSource 修改。

public class DataSourceConfiguringBeanPostProcessor implements BeanPostProcessor {
    private final Map<String,String> properties = new HashMap<>;

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instance BasicDataSource ) { 
            for (Map.Entry<String, String> prop : properties.entrySet()) {
                ((BasicDataSource) bean).addConnectionProperty(prop.getKey(), prop.getValue());
            }
        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public void setProperties(Map<String, String> properties) {
        this.properties.putAll(properties);
    }
}

现在您可以将它添加到您的配置中,它会将属性添加到 DataSource 个 bean。

@Bean
public BeanPostProcessor dataSourcePostProcessor() {
    DataSourceConfiguringBeanPostProcessor processor = new DataSourceConfiguringBeanPostProcessor();
    Map<String, String> properties = new HashMap<>();
    properties.put("defaultRowPrefetch", "15");
    properties.put("defaultBatchValue", "25");
    processor.setProperties(properties);
    return processor;
}

这应该可以解决配置数据源的问题。