【发布时间】: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());
}
}
}
- 好像我的游泳池漏水了。我没有将连接正确返回到池中。
- 有没有更优雅的方式来使用
jdbcTemplate和preparedStatement.setFetchSize(30000);
【问题讨论】:
标签: java postgresql spring-boot jdbc hikaricp