美文网首页工作小记
JAVA学习日记-自定义数据库连接池类

JAVA学习日记-自定义数据库连接池类

作者: 叫子非鱼啊 | 来源:发表于2020-06-04 20:41 被阅读0次

    当有多个线程,每个线程都需要连接数据库执行SQL语句的话,那么每个线程都会创建一个连接,并且在使用完毕后,关闭连接。

    创建连接和关闭连接的过程也是比较消耗时间的,当多线程并发的时候,系统就会变得很卡顿。

    同时,一个数据库同时支持的连接总数也是有限的,如果多线程并发量很大,那么数据库连接的总数就会被消耗光,后续线程发起的数据库连接就会失败。

    原理

    与传统方式不同,连接池在使用之前,就会创建好一定数量的连接。
    如果有任何线程需要使用连接,那么就从连接池里面借用,而不是自己重新创建.
    使用完毕后,又把这个连接归还给连接池供下一次或者其他线程使用。
    倘若发生多线程并发情况,连接池里的连接被借用光了,那么其他线程就会临时等待,直到有连接被归还回来,再继续使用。
    整个过程,这些连接都不会被关闭,而是不断的被循环使用,从而节约了启动和关闭连接的时间。

    package jdbc;
      
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
      
    public class ConnectionPool {
      
        List<Connection> cs = new ArrayList<Connection>();
      
        int size;
      
        public ConnectionPool(int size) {
            this.size = size;
            init();
        }
      
        public void init() {
              
            //这里恰恰不能使用try-with-resource的方式,因为这些连接都需要是"活"的,不要被自动关闭了
            try {
                Class.forName("com.mysql.jdbc.Driver");
                for (int i = 0; i < size; i++) {
                    Connection c = DriverManager
                            .getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");
      
                    cs.add(c);
      
                }
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
      
        public synchronized Connection getConnection() {
            while (cs.isEmpty()) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Connection c = cs.remove(0);
            return c;
        }
      
        public synchronized void returnConnection(Connection c) {
            cs.add(c);
            this.notifyAll();
        }
      
    }
    

    测试

    package jdbc;
      
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.Statement;
     
    import jdbc.ConnectionPool;
       
    public class TestConnectionPool {
       
        public static void main(String[] args) {
            ConnectionPool cp = new ConnectionPool(3);
            for (int i = 0; i < 100; i++) {
                new WorkingThread("working thread" + i, cp).start();
            }
       
        }
    }
       
    class WorkingThread extends Thread {
        private ConnectionPool cp;
       
        public WorkingThread(String name, ConnectionPool cp) {
            super(name);
            this.cp = cp;
        }
       
        public void run() {
            Connection c = cp.getConnection();
            System.out.println(this.getName()+ ":\t 获取了一根连接,并开始工作"  );
            try (Statement st = c.createStatement()){
                 
                //模拟时耗1秒的数据库SQL语句
                Thread.sleep(1000);
                st.execute("select * from hero");
       
            } catch (SQLException | InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cp.returnConnection(c);
        }
    }
    

    相关文章

      网友评论

        本文标题:JAVA学习日记-自定义数据库连接池类

        本文链接:https://www.haomeiwen.com/subject/glunzhtx.html