zoukankan      html  css  js  c++  java
  • 自定义连接池

    由于jdbc操作数据库时会经常创建和销毁连接,造成资源消耗,所以引入连接池。

    连接池是存储Connection对象的容器,因为要经常对这个容器操作,我们用LinkedList来存储。

    之前我们关闭连接,调用close()方法,销毁Connection对象,引入连接池后,是把这个对象回收到连接池中,不是销毁。

    自定义连接池要实现DataSource接口,此接口在javax.sql下,重写getConnection()方法。

    自定义连接池:

    package cn.sasa.pool;
    
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.SQLFeatureNotSupportedException;
    import java.util.LinkedList;
    import java.util.logging.Logger;
    
    import javax.sql.DataSource;
    
    import cn.sasa.utils.DBUtils;
    
    //自定义连接池
    //实现DataSource接口,注意是javax.sql下的DataSource
    public class MyPool implements  DataSource{
        //准备一个池子用于存储Connection对象,因为要频繁操作,用LinkedList接收。
        private static LinkedList<Connection> pool = new LinkedList<Connection>();
        
        //创建连接放到池子中
        static {
            for(int i=0;i<5;i++) {
                Connection conn = DBUtils.getConnection();
                //改造conn
                MyConnection myconn = new MyConnection(conn, pool);
                pool.add(myconn);
            }
        }
        
        /**
         * 获取连接对象
         */
        @Override
        public Connection getConnection() throws SQLException {
            Connection conn = null;
            //使用前先判断有没有
            if(pool.size()==0) {
                for(int i=0;i<5;i++) {
                    conn = DBUtils.getConnection();
                    //改造conn
                    MyConnection myconn = new MyConnection(conn, pool);
                    pool.add(myconn);
                }
            }
            //获取一个连接对象
            return pool.remove(0);
        }
        
        @Override
        public Logger getParentLogger() throws SQLFeatureNotSupportedException {
            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 Connection getConnection(String username, String password) throws SQLException {
            return null;
        }
    
        @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;
        }
    }

    包装Connection

    package cn.sasa.pool;
    
    import java.sql.Array;
    import java.sql.Blob;
    import java.sql.CallableStatement;
    import java.sql.Clob;
    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.NClob;
    import java.sql.PreparedStatement;
    import java.sql.SQLClientInfoException;
    import java.sql.SQLException;
    import java.sql.SQLWarning;
    import java.sql.SQLXML;
    import java.sql.Savepoint;
    import java.sql.Statement;
    import java.sql.Struct;
    import java.util.LinkedList;
    import java.util.Map;
    import java.util.Properties;
    import java.util.concurrent.Executor;
    
    //为conn调用close()回收到连接池中
    public class MyConnection implements Connection{
    
        private Connection conn;
        private LinkedList<Connection> pool;
        
        public MyConnection(Connection conn, LinkedList<Connection> pool) {
            this.conn = conn;
            this.pool = pool;
        }
        
        //增强close方法
        @Override
        public void close() throws SQLException {
            pool.add(conn);
        }
        
        //重写此方法,否则报空指针异常
        @Override
        public PreparedStatement prepareStatement(String sql) throws SQLException {
            return conn.prepareStatement(sql);
        }
        
        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            return null;
        }
    
        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            return false;
        }
    
        @Override
        public Statement createStatement() 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 {
        }
    
        @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;
        }
    
    }

    测试:

    package cn.sasa.test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import javax.sql.DataSource;
    
    import cn.sasa.pool.MyPool;
    import cn.sasa.utils.DBUtils;
    
    public class TestPool {
    
        public static void main(String[] args) {
            
            //自定义连接池,使用增强close()
            Connection conn = null;
            PreparedStatement pstate = null;
            DataSource pool = new MyPool();
            ResultSet rs = null;
            try {
                conn = pool.getConnection();
                String sql = "select * from user where name=?";
                pstate = conn.prepareStatement(sql);
                pstate.setString(1, "test");
                rs = pstate.executeQuery();
                while(rs.next()) {
                    System.out.println(rs.getString("name"));
                }
            }catch(Exception e) {
                throw new RuntimeException(e);
            }finally {
                DBUtils.release(rs, pstate, conn);
            }
        }
    
    }

    工具类:

    package cn.sasa.utils;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ResourceBundle;
    
    public class DBUtils {
        private static Connection conn = null;
        private static String driver = null;
        private static String url = null;
        private static String user = null;
        private static String pwd = null;
        //注册驱动
        static {
            try {
                ResourceBundle bundle = ResourceBundle.getBundle("database");
                driver = bundle.getString("driver");
                url = bundle.getString("url");
                user = bundle.getString("user");
                pwd = bundle.getString("pwd");
                Class.forName(driver);
                conn = DriverManager.getConnection(url, user, pwd);
            }catch(Exception e) {
                throw new RuntimeException(e);
            }
        }
        
        //获取连接对象
        public static Connection getConnection() {
            return conn;
        }
        
        //销毁资源 查询
        public static void release(ResultSet rs, PreparedStatement state, Connection conn ) {
            if(rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(state != null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
        //销毁资源 增删改
        public static void release(PreparedStatement state, Connection conn) {
            if(state != null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    数据库配置文件略。

  • 相关阅读:
    深入Java虚拟机(4)——网络移动性
    安装ftp碰到的问题及解决方法
    6.设置ListView的Item的高度无效
    hdu1181(变形课)
    ZooKeeper分布式集群部署及问题
    管理线程之创建线程
    Linux系统编程——多线程实现多任务
    Request.Params用法,后台接收httpget参数
    resharper警告 :linq replace with single call to FirstOrDefault
    SQL Prompt几个快捷键
  • 原文地址:https://www.cnblogs.com/SasaL/p/10559071.html
Copyright © 2011-2022 走看看