数据库连接池

作者: 小小蒜头 | 来源:发表于2017-09-28 21:39 被阅读32次

    使用数据库连接池优化程序性能

    直接获取链接缺点 性能的优化

    编写数据库连接池

    • 编写连接池需事先java.sql.DataSource接口。DateSource接口中定义了两个重载的getConnection方法:
      Connection getConnection()
      Connection getConnection(String username,String password)

    • 实现DataSource接口,并实现连接池功能的步骤:

    1. 在DataSource构造函数中批量创建与数据库的连接,并把创建的连接加入LinkedList对象中;
    2. 实现getConnection方法,让getConnection方法每次调用时,从LinkedList中取一个Connection返回给用户;
    3. 当用户使用完Connection,调用Connection.close方法时,Connection对象应保证将自己返回到LinkedList中,而不要把Conn还给数据库。

    难点:Connection保证将自己返回到LinkedList中

    演示

    1. 建一个JdbcPool类,实现DataSource接口,里面我都有写较为详细的注释。

    package cn.itcast.utils;
    
    import javax.sql.DataSource;
    import java.io.PrintWriter;
    import java.sql.*;
    import java.util.LinkedList;
    import java.util.Map;
    import java.util.Properties;
    import java.util.concurrent.Executor;
    import java.util.logging.Logger;
    
    /**
     * Created by yvettee on 2017/9/28.
     */
    public class JdbcPool implements DataSource {
        private static LinkedList<Connection> list = new LinkedList<Connection>();
        private static Properties prop = new Properties();
    
        //初始化时,要找连接池要一批链接的操作做一次就够
        static {
            try {
                prop.load(JdbcPool.class.getClassLoader().getResourceAsStream("db.properties"));
                Class.forName(prop.getProperty("driver"));
    
                //一上来就要10个连接
                for (int i = 0; i < 10; i++) {
                    Connection conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password"));
                    list.add(conn);
                }
            } catch (Exception e) {
                throw new ExceptionInInitializerError(e);
            }
        }
    
    
        @Override
        public Connection getConnection() throws SQLException {
            if (list.size() <= 0) {
                throw new RuntimeException("数据库忙,请稍后再来!");
            }
            //(链表)始终把第一个链接拿走
            Connection conn = list.removeFirst();
            // conn.close();这里不能直接关闭,因为会把链接还给数据库,
            // 我们的目的是从池里拿链接,也要还给池里
           MyConnection my = new MyConnection(conn);
            /*
            在实际开发,发现对象的方法满足不了开发需求时,有以下几种方法:
            1.写一个connection子类,覆盖并增强close方法(不可用)
            2.用包装设计模式(这里采用这个)
            3.用动态代理
             */
            return my;
        }
    
        //包装模式,1.实现与被增强对象的相同接口
        class MyConnection implements Connection {
    
            //2.在类中定义一个变量,记住被增强对象
            private Connection conn;
    
            //3.定义一个构造函数
            public MyConnection(Connection conn) {
                this.conn = conn;
            }
    
            //4.覆盖想增强的方法
            public void close() {
                list.add(this.conn);
            }
    
            @Override
            public Statement createStatement() throws SQLException {
                //5.对于不想增强的方法,直接调用目标对象(被增强对象)的方法
                return this.conn.createStatement();
            }
    
            @Override
            public PreparedStatement prepareStatement(String sql) throws SQLException {
                return null;
            }
    
            @Override
            public CallableStatement prepareCall(String sql) throws SQLException {
                return null;
            }
    
            @Override
            public String nativeSQL(String sql) throws SQLException {
                return null;
            }
    
            @Override
            public void setAutoCommit(boolean autoCommit) throws SQLException {
    
            }
    
            @Override
            public boolean getAutoCommit() throws SQLException {
                return false;
            }
    
            @Override
            public void commit() throws SQLException {
    
            }
    
            @Override
            public void rollback() throws SQLException {
    
            }
    
            @Override
            public boolean isClosed() throws SQLException {
                return false;
            }
    
            @Override
            public DatabaseMetaData getMetaData() throws SQLException {
                return null;
            }
    
            @Override
            public void setReadOnly(boolean readOnly) throws SQLException {
    
            }
    
            @Override
            public boolean isReadOnly() throws SQLException {
                return false;
            }
    
            @Override
            public void setCatalog(String catalog) throws SQLException {
    
            }
    
            @Override
            public String getCatalog() throws SQLException {
                return null;
            }
    
            @Override
            public void setTransactionIsolation(int level) throws SQLException {
    
            }
    
            @Override
            public int getTransactionIsolation() throws SQLException {
                return 0;
            }
    
            @Override
            public SQLWarning getWarnings() throws SQLException {
                return null;
            }
    
            @Override
            public void clearWarnings() throws SQLException {
                this.conn.clearWarnings();
            }
    
            @Override
            public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
                return null;
            }
    
            @Override
            public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
                return null;
            }
    
            @Override
            public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
                return null;
            }
    
            @Override
            public Map<String, Class<?>> getTypeMap() throws SQLException {
                return null;
            }
    
            @Override
            public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
    
            }
    
            @Override
            public void setHoldability(int holdability) throws SQLException {
    
            }
    
            @Override
            public int getHoldability() throws SQLException {
                return 0;
            }
    
            @Override
            public Savepoint setSavepoint() throws SQLException {
                return null;
            }
    
            @Override
            public Savepoint setSavepoint(String name) throws SQLException {
                return null;
            }
    
            @Override
            public void rollback(Savepoint savepoint) throws SQLException {
    
            }
    
            @Override
            public void releaseSavepoint(Savepoint savepoint) throws SQLException {
    
            }
    
            @Override
            public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
                return null;
            }
    
            @Override
            public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
                return null;
            }
    
            @Override
            public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
                return null;
            }
    
            @Override
            public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
                return null;
            }
    
            @Override
            public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
                return null;
            }
    
            @Override
            public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
                return null;
            }
    
            @Override
            public Clob createClob() throws SQLException {
                return null;
            }
    
            @Override
            public Blob createBlob() throws SQLException {
                return null;
            }
    
            @Override
            public NClob createNClob() throws SQLException {
                return null;
            }
    
            @Override
            public SQLXML createSQLXML() throws SQLException {
                return null;
            }
    
            @Override
            public boolean isValid(int timeout) throws SQLException {
                return false;
            }
    
            @Override
            public void setClientInfo(String name, String value) throws SQLClientInfoException {
    
            }
    
            @Override
            public void setClientInfo(Properties properties) throws SQLClientInfoException {
    
            }
    
            @Override
            public String getClientInfo(String name) throws SQLException {
                return null;
            }
    
            @Override
            public Properties getClientInfo() throws SQLException {
                return null;
            }
    
            @Override
            public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
                return null;
            }
    
            @Override
            public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
                return null;
            }
    
            @Override
            public void setSchema(String schema) throws SQLException {
    
            }
    
            @Override
            public String getSchema() throws SQLException {
                return null;
            }
    
            @Override
            public void abort(Executor executor) throws SQLException {
    
            }
    
            @Override
            public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
    
            }
    
            @Override
            public int getNetworkTimeout() throws SQLException {
                return 0;
            }
    
            @Override
            public <T> T unwrap(Class<T> iface) throws SQLException {
                return null;
            }
    
            @Override
            public boolean isWrapperFor(Class<?> iface) throws SQLException {
                return false;
            }
        }
    
        @Override
        public Connection getConnection(String username, String password) throws SQLException {
            return null;
        }
    
        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            return null;
        }
    
        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            return false;
        }
    
        @Override
        public PrintWriter getLogWriter() throws SQLException {
            return null;
        }
    
        @Override
        public void setLogWriter(PrintWriter out) throws SQLException {
    
        }
    
        @Override
        public void setLoginTimeout(int seconds) throws SQLException {
    
        }
    
        @Override
        public int getLoginTimeout() throws SQLException {
            return 0;
        }
    
        @Override
        public Logger getParentLogger() throws SQLFeatureNotSupportedException {
            return null;
        }
    }
    
    

    相关文章

      网友评论

        本文标题:数据库连接池

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