HikariPool连接池的使用
测试代码: 使用连接池用时500ms, 不使用连接池用时8s, 相差16倍.
每个连接的创建都要经过http握手、密码认证,这里比较耗时, mysql给每个connection分配一个id
public class DBpoolTest { private static final HikariDataSource ds; static { HikariConfig conf = new HikariConfig(); conf.setUsername("root"); conf.setPassword("root"); conf.setJdbcUrl("jdbc:mysql://localhost:3306/abc"); ds = new HikariDataSource(conf); } @Test public void test_1() throws SQLException { long st = System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { Connection connection = ds.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select now() from dual"); while (resultSet.next()) { System.out.println(resultSet.getString(1)); } connection.close(); } System.out.println(System.currentTimeMillis() - st); } @Test public void test_2() throws SQLException { long st = System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/abc", "root", "root"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select now() from dual"); while (resultSet.next()) { System.out.println(resultSet.getString(1)); } connection.close(); } System.out.println(System.currentTimeMillis() - st); } }
连接池回收过程
HikariDataSource datasource= new HikariDataSource( xxxx );
Connection cn = datasource.getConnection();
try {
cn.doXXX()
} finnally(){
connection.close();// connection的实现类(代理类)自己会调用hikariPool.evictConnection(cn) ,将此连接回收到pool中
}
connection回收到池中是连接池自己做的事, 业务代码不用关心物理连接是否真的关闭,只需要调用close()方法
Hikari中connection.close()的实现
Druid close()实现
@@@build beautiful things, share happiness@@@