自定义数据库连接池

来源:互联网 发布:可编辑照片的软件 编辑:程序博客网 时间:2024/05/15 23:46

编写连接池需要实现java.sql.DataSource接口.DataSource接口定义了两个重载的getConnection
方法:
Connection getConnection()
Connection getConnection(String username,String password)
实现DataSource接口,并实现连接池功能的步骤:
在/DataSource构造函数中批量创建与数据库的连接,并把创建的连接加入LinkedList对象中
实现getConnection方法,让getConnection方法每次调用时,从LinkedList中取出一个Connection
返回给用户
当用户使用完Connection,让Connection.close()方法是,Collection对象应保证将自己返回到
LinkedList中,而不要conn还给数据库?
这是我的解决方案:

package com.ds.mydatabasepool;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.SQLFeatureNotSupportedException;import java.util.LinkedList;import java.util.List;import java.util.Properties;import java.util.logging.Logger;import java.util.Collections;import javax.sql.DataSource;/** * @author 董硕: * @version 创建时间:2017年9月2日 上午8:29:35 *  以上内容调用一次就创建一个connection对象 *//** * @author job * */public class MyPool implements DataSource {    private static List<Connection> connections = Collections.synchronizedList(new LinkedList<>());    static {        InputStream is = MyPool.class.getClassLoader().getResourceAsStream("database.propreties");        Properties propreties = new Properties();        try {            propreties.load(is);            String driver = propreties.getProperty("driver");            String url = propreties.getProperty("url");            String username = propreties.getProperty("username");            String password = propreties.getProperty("password");            Class.forName(driver);            for (int i = 0; i < 5; i++) {                Connection conn = DriverManager.getConnection(url, username, password);                connections.add(conn);            }        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    @Override    public Connection getConnection() throws SQLException {        // TODO Auto-generated method stub        Connection connection = connections.remove(0);// 在集合中取出一个一个connection                                                        // 并返回        System.out.println("取出一个" + "------" + connection.hashCode());        System.out.println("池子中剩余" + connections.size());        return connection;    }    public void release(Connection connection) {        connections.add(connection);        System.out.println("放回一个"+"------"+connection.hashCode());        System.out.println("池子中剩余"+connections.size());    }    @Override    public PrintWriter getLogWriter() throws SQLException {        // TODO Auto-generated method stub        return null;    }    @Override    public void setLogWriter(PrintWriter out) throws SQLException {        // TODO Auto-generated method stub    }    @Override    public void setLoginTimeout(int seconds) throws SQLException {        // TODO Auto-generated method stub    }    @Override    public int getLoginTimeout() throws SQLException {        // TODO Auto-generated method stub        return 0;    }    @Override    public Logger getParentLogger() throws SQLFeatureNotSupportedException {        // TODO Auto-generated method stub        return null;    }    @Override    public <T> T unwrap(Class<T> iface) throws SQLException {        // TODO Auto-generated method stub        return null;    }    @Override    public boolean isWrapperFor(Class<?> iface) throws SQLException {        // TODO Auto-generated method stub        return false;    }    @Override    public Connection getConnection(String username, String password) throws SQLException {        // TODO Auto-generated method stub        return null;    }}

这是运行结果

这样写并不是很好,Apache公司已经写出更好的方法
连接池DBCP使用 apache上的java连接池项目,也是tomcat使用的连接池组件
单独使用dbcp 需要3个jar包 comments-dbcp commons-pool commons-logging-1.2
BasicDataSourceFactory.createDataSource(database.properties)可以获取到BasicDataSource对象

private static  BasicDataSource basicDataSource=null;    static{        try {            String name="database.propreties";            InputStream inStream=Utils.class.getClassLoader().getResourceAsStream(name);            Properties properties=new Properties();            properties.load(inStream);            basicDataSource=BasicDataSourceFactory.createDataSource(properties);            //          driver=properties.getProperty("driver");//          url=properties.getProperty("url");//          username=properties.getProperty("username");//          password=properties.getProperty("password");//          Class.forName(driver);        } catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }
原创粉丝点击