【问题标题】:SpringBoot how to set connection fetch size for Hikari Pool and jdbcTemplateSpring Boot 如何为 Hikari Pool 和 jdbcTemplate 设置连接获取大小
【发布时间】:2021-08-16 18:42:06
【问题描述】:

我正在寻找方法

  • 为 Spring DataSource 配置 Hikari 连接池
  • 为 resultSet 显式设置 fetchSize。

这是我的 application.properties

# Datasource
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:postgresql://mydb
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driverClassName=org.postgresql.Driver
#Hikari
spring.datasource.hikari.connectionTimeout=30000
spring.datasource.hikari.idleTimeout=600000
spring.datasource.hikari.maxLifetime=1800000
spring.datasource.hikari.maximum-pool-size=100
spring.datasource.hikari.auto-commit=true

这是我的服务代码


@Service
@RequiredArgsConstructor
public class PerfService {

    private final JdbcTemplate template;

    public RowCountResponse getData(String param) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = Objects.requireNonNull(template.getDataSource()).getConnection();
          
            preparedStatement = connection.prepareStatement("SELECT whatever");
            preparedStatement.setFetchSize(30000); // !!!
            preparedStatement.setString(1, param);
          
            ResultSet resultSet = preparedStatement.executeQuery();
            int rowCount = 0;
            while (resultSet.next()) {
                rowCount++;
            }

            resultSet.close();
            return new RowCountResponse()
                    .setRowCount(rowCount);
        } catch (Exception e) {
            throw new RuntimeException("Error while fetching rows", e);
        } finally {
            JdbcUtils.closeStatement(preparedStatement);
            DataSourceUtils.releaseConnection(connection, template.getDataSource());
        }
    }
}
  • 好像我的游泳池漏水了。我没有将连接正确返回到池中。
  • 有没有更优雅的方式来使用jdbcTemplatepreparedStatement.setFetchSize(30000);

【问题讨论】:

    标签: java postgresql spring-boot jdbc hikaricp


    【解决方案1】:

    抱歉迟到了,不过可以帮到别人。

    设置 fetchSize 时 postgresql 出现问题 - https://github.com/spring-projects/spring-framework/issues/24848

    为了工作,您还必须为您的连接设置 autoCommit=false,所以在您的示例中,它将是:

    spring.datasource.hikari.auto-commit=false
    

    但是将连接池的自动提交设置为 false 可能不方便,因此一种解决方法是拥有两个连接池 - 一个是 autoCommit=false 的只读连接池,另一个是 autoCommit=true 的第二个(普通)连接池。

    JdbcTemplate 也有 setFetchSize 方法,所以你可以简单地做

    template.setFetchSize(30000); 
    

    【讨论】:

      【解决方案2】:

      可以使用连接参数defaultRowFetchSize,见the documentation

      【讨论】:

      • 感谢您的回复,如何将其集成到 SpringBoot 中?