SpringBoot 如何为 Hikari Pool 和 jdbcTemplate 设置连接获取大小

时间:2021-05-28 13:53:42

标签: java postgresql spring-boot jdbc hikaricp

我正在寻找一种方法

  • 为 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);

1 个答案:

答案 0 :(得分:0)

您可以使用连接参数 defaultRowFetchSize,请参阅 the documentation