一、池化设计模式
-----------------------------------------------------------------
    1.使用有限的对象去服务于大量的客户端


二、使用第三方开元的连接池实现
-----------------------------------------------------------------
1.c3p0

  

  /**
     * 测试c3p0连接池
     */
    public static void tsC3P0()
    {
        try {
            //创建连接池
            ComboPooledDataSource ds = new ComboPooledDataSource();
            //加载驱动
            ds.setDriverClass("com.mysql.jdbc.Driver");
            //设定url
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/mydata");
            //
            ds.setUser("mysql");
            ds.setPassword("mysql");
            ds.setMaxPoolSize(10);        //池子最大连接数
            ds.setMinPoolSize(2);        //池子最小连接数
            ds.setInitialPoolSize(3);    //池子初始化连接数
            ds.setAcquireIncrement(2);    //每次增加2个连接
            
            //
            Connection conn =  ds.getConnection();
            PreparedStatement pt = conn.prepareStatement("insert into customers (name) values('v1')");
            pt.executeUpdate();
            pt.close();
            conn.close();
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }


2.DBCP

  

  /**
     * 测试dbcp连接池
     */
    public static void tsDBCP()
    {
        try {
            //创建连接池
            BasicDataSource ds = new BasicDataSource();
            //加载驱动
            ds.setDriverClassName("com.mysql.jdbc.Driver");
            //设定url
            ds.setUrl("jdbc:mysql://localhost:3306/mydata");
            //
            ds.setUsername("mysql");
            ds.setPassword("mysql");
            ds.setMaxTotal(10);        //池子最大连接数
            ds.setInitialSize(3);    //池子初始化连接数
            
            
            //
            Connection conn =  ds.getConnection();
            PreparedStatement pt = conn.prepareStatement("insert into customers (name) values('v2')");
            pt.executeUpdate();
            pt.close();
            conn.close();
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


三、自定义连接池
------------------------------------------------------------------
1.类结构图

 

2.代码区

----------------------------------------------------------
*******Part1.TsMain   测试主函数
------------------------------------------------------------

/**
 * 测试自定义数据源
 */
public class TsMain {

    public static void main(String[] args) {
        
        try {
            
            MyDataSource dt = new MyDataSource();
            //1.
            Connection conn = dt.getConnection();
            PreparedStatement pt = conn.prepareStatement("insert into customers (name) values('xxx1')");
            pt.executeUpdate();
            pt.close();
            conn.close();
            //2.
            conn = dt.getConnection();
            pt = conn.prepareStatement("insert into customers (name) values('xxx2')");
            pt.executeUpdate();
            pt.close();
            conn.close();
            //3.
            conn = dt.getConnection();
            pt = conn.prepareStatement("insert into customers (name) values('xxx3')");
            pt.executeUpdate();
            pt.close();
            conn.close();
            
            
        } catch (SQLException e) {

            e.printStackTrace();
        }
        
    }
    
}


----------------------------------------------------------
*******Part2.TsMain   自定义数据源 
------------------------------------------------------------

/**
 * 自定义数据源 
 */
public class MyDataSource implements DataSource{

    //连接池
    private ConnectionPool pool;
    
    public MyDataSource()
    {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/mydata";
        String user = "mysql";
        String password = "mysql";
        pool = new ConnectionPool(driver, url, user, password);
        pool.init();
    }
    
    
    
    @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;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    /**
     * 获取连接
     */
    public Connection getConnection() throws SQLException {
        
        return pool.getConn();
        
    }

    @Override
    public Connection getConnection(String username, String password)
            throws SQLException {
        return null;
    }

}


----------------------------------------------------------
*******Part3.TsMain   自定义连接池 
------------------------------------------------------------

/**
 * 连接池
 */
public class ConnectionPool {

    //最大连接数
    private int max = 2;
    //连接的集合
    private List<Connection> connections = new ArrayList<Connection>();
    
    //连接驱动
    private String driver;
    //数据库url
    private String url;
    private String user;
    private String password;
    

    public ConnectionPool(String driver, String url, String user,
            String password) {
        this.driver = driver;
        this.url = url;
        this.user = user;
        this.password = password;
        
        //加载驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    //初始化连接池
    public void init()
    {
        for(int i = 0 ; i < max ; i ++)
        {
            try {
                
                //获取连接
                Connection conn = DriverManager.getConnection(url, user, password);
                MyConnection myConn = new MyConnection(conn, this);
                connections.add(myConn);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    /**
     * 回收连接
     * @param conn 回收的连接
     */
    public void recyleConn(MyConnection conn) {
        
        connections.add(conn);
    }
    
    /**
     * 释放连接
     */
    public Connection getConn()
    {
        if(connections.isEmpty())
        {
            System.out.println("pool is empty");
            return null;
        }
        else
        {
            return connections.remove(0);
        }
    }
    
}


-------------------------------------------------------------------------
*******Part4.ConnectionAdapter 连接的适配器(适配器模式)
-------------------------------------------------------------------------------

/**
 * 连接适配器 
 */
public abstract class ConnectionAdapter implements Connection{

//注:此处方法太多,不贴了
//只要引用接口Connection,并实现其方法即可

}


----------------------------------------------------------
*******Part5.自定义连接类(装饰模式)
******主要在于重写getConnectio()方法
------------------------------------------------------------

/**
 * 自定义数据源 
 */
public class MyDataSource implements DataSource{

    //连接池
    private ConnectionPool pool;
    
    public MyDataSource()
    {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/mydata";
        String user = "mysql";
        String password = "mysql";
        pool = new ConnectionPool(driver, url, user, password);
        pool.init();
    }
    
    
    
    @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;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    /**
     * 获取连接
     */
    public Connection getConnection() throws SQLException {
        
        return pool.getConn();
        
    }

    @Override
    public Connection getConnection(String username, String password)
            throws SQLException {
        return null;
    }

}


 

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐