測試代碼: 使用連接池用時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()實現


