简介
HikariCP是由日本程序员开源的一个数据库连接池组件,代码非常轻量,并且速度非常的快。根据官方提供的数据,在i7,开启32个线程32个连接的情况下,进行随机数据库读写操作,HikariCP的速度是现在常用的C3P0数据库连接池的数百倍。
在SpringBoot2.0中,官方也是推荐使用HikariCP。
HikariCP之所以快是因为:
- 字节码更加精简,所以可以加载更多代码到缓存。
- 实现了一个无锁的集合类型,来减少并发造成的资源竞争。
- 使用了自定义的数组类型,相对与ArrayList极大地提升了性能。
- 自定义集合类型(ConcurrentBag):提高并发读写的效率
- 针对CPU的时间片算法进行优化,尽可能在一个时间片里面完成各种操作。
com.zaxxer
HikariCP
3.4.2
mysql
mysql-connector-java
8.0.19
第二步:编写HikariCP配置文件HikariCP.properties
jdbcUrl=jdbc:mysql://localhost:3306/db_test?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false
driverClassName=com.mysql.cj.jdbc.Driver
dataSource.user=root
dataSource.password=root
dataSource.maximumPoolSize=10
编写连接池工具类:
public class DBUtils {
public static Connection getConnection() {
HikariConfig config = new HikariConfig(DBUtils .class.getClassLoader().getResource("hikaricp.properties").getPath());
HikariDataSource ds = new HikariDataSource(config);
Connection conn = null;
try {
conn = ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void closeConnection(Connection conn){
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
编写测试代码:
public static void main(String[] args) throws SQLException {
Connection conn = DBUtils.getConnection();
System.out.println(conn);
Statement stmt = conn.createStatement();
String sql = "select * from tb_dept";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getInt("deptno") + "\t" + rs.getString("dname") + "\t" + rs.getString("loc"));
}
}
SpringBoot整合 HikariCP
POM
com.zaxxer
HikariCP
${hikaricp.version}
org.springframework.boot
spring-boot-starter-jdbc
org.apache.tomcat
tomcat-jdbc
mysql
mysql-connector-java
${mysql.version}
application.yml
spring:
datasource:
hikari:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
minimum-idle: 5
idle-timeout: 600000
maximum-pool-size: 10
auto-commit: true
pool-name: MyHikariCP
max-lifetime: 1800000
connection-timeout: 30000
connection-test-query: SELECT 1