zoukankan      html  css  js  c++  java
  • 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()实现









  • 相关阅读:
    代替gets()的新操作
    前缀和(一维与二维) 差分
    高精度(高精加,高精减,高精乘,高精除)
    提高cin cout的速度
    二分算法(以 数的范围 为例)
    归并排序(merge_sort)
    快速排序(quick_sort)
    由后缀表达式题目:stoi atoi 函数新发现
    Redis(二)
    每日算法练习(2020-1-11)
  • 原文地址:https://www.cnblogs.com/yszzu/p/10192206.html
Copyright © 2011-2022 走看看