HikariPool连接池的使用

 

 

 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()实现

 




测试代码: 使用连接池用时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);
    }
}

  











转载于:https://www.cnblogs.com/yszzu/p/10192206.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值