使用数据库连接池-HikariCP解决JDBC原生速度太慢问题
引入依赖<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP --><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>2.5.1<
·
引入依赖
<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.5.1</version>
</dependency>
<!--oracle连接工具-->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>12.1.0.2.0</version>
</dependency>
编写配置文件:hikari.properties
jdbcUrl=jdbc:oracle:thin:@192.168.x.xx:1521:orcl
driverClassName=oracle.jdbc.driver.OracleDriver
dataSource.user=root
dataSource.password=root
dataSource.maximumPoolSize=100
接口实现类调用,使用静态代码块和饿汉模式
@Service
public class RealEstateServiceImpl implements RealEstateService {
private static HikariDataSource hikariDataSource;
// 静态代码块,只需要加载一次
static {
HikariConfig config = new HikariConfig("src/main/resources/hikari.properties");
hikariDataSource = new HikariDataSource(config);
}
// 定义提供连接对象的方法
// 饿汉模式
private Connection conn() {
try {
// 获取连接对象
return hikariDataSource.getConnection();
} catch (Exception e) {
e.getMessage();
}
return null;
}
//测试
@Override
public List<String> getCLFDJ() {
//获取年份和区域
List<String> years = queryCLFDJAllYear();
return years;
}
//查询表中的所有年份
private List<String> queryCLFDJAllYear() {
List<String> list = new ArrayList<>();
// try with自动关闭
try (Connection conn = conn()) {
//预编译
String selectSql = "SELECT YEAR FROM BDCTJ_CLFDJ GROUP BY YEAR ORDER BY YEAR";
PreparedStatement ptmt = conn.prepareStatement(selectSql); //预编译SQL,减少sql执行
//执行,求所有
ResultSet resultSet = ptmt.executeQuery();
while (resultSet.next()) {
list.add(resultSet.getString("YEAR"));
}
ptmt.close();
resultSet.close();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return list;
}
}
更多推荐




所有评论(0)