归还代理模式

归还连接

在这里插入图片描述

package com.itheima01;

import com.itheima.utils.JDBCUtils;
import com.itheima02.MyConnection2;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

/*
    自定义数据库连接池
 */
public class MyDataSource implements DataSource {
    /// 准备容器,用于保存多个连接对象
    private static List<Connection> pool= Collections.synchronizedList(new ArrayList<>()); /// 线程安全
    /// 定义静态代码块,通过工具类获取10个连接对象
    static
    {
        for (int i=1;i<=10;i++)
        {
            Connection connection = JDBCUtils.getConnection();
            pool.add(connection);
        }
    }

    ///重写getConnection 获取连接对象使用

    @Override
    public Connection getConnection() throws SQLException {
       if(pool.size()>0)
       {
           Connection connection=pool.remove(0);

           ///通过自定义的链接对象,对原有的链接对象进行包装
           MyConnection2 connection2 = new MyConnection2(connection,pool);
            return connection2;
       }
       else
       {
           throw new RuntimeException("连接数量用尽");
       }
    }

    /// 定义getSize方法 获取连接池容器的大小
    public int getSize()
    {
        return pool.size();
    }

    @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;
    }
}

装饰设计模式
在这里插入图片描述

package com.itheima02;

import java.sql.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/*
    定义一个类 实现Connection接口
    定义连接对象和连接池容器对象的成员变量
    通过有参构造方法为成员变量赋值
    重写close方法 完成归还连接
    剩余方法,还是调用原有的连接对象中的功能即可
 */
public class MyConnection2 implements Connection {

    /// 定义连接对象和连接池容器对象的成员变量
    private Connection connection;
    private List<Connection> pool;

    ///通过有参构造方法为成员变量赋值
    public  MyConnection2(Connection connection,List<Connection> pool)
    {
        this.connection=connection;
        this.pool=pool;
    }

    ///重写close方法 完成归还连接
    @Override
    public void close() throws SQLException {
        pool.add(connection);
    }
    @Override
    public Statement createStatement() throws SQLException {
        return connection.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        return connection.prepareCall(sql);
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return connection.nativeSQL(sql);
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        connection.setAutoCommit(autoCommit);
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return connection.getAutoCommit();
    }

    @Override
    public void commit() throws SQLException {
        connection.commit();
    }

    @Override
    public void rollback() throws SQLException {
        connection.rollback();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return connection.isClosed();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return connection.getMetaData();
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {
        connection.setReadOnly(readOnly);
    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return connection.isReadOnly();
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {
        connection.setCatalog(catalog);
    }

    @Override
    public String getCatalog() throws SQLException {
        return connection.getCatalog();
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {
        connection.setTransactionIsolation(level);
    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return connection.getTransactionIsolation();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return connection.getWarnings();
    }

    @Override
    public void clearWarnings() throws SQLException {
        connection.clearWarnings();
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return connection.createStatement(resultSetType,resultSetConcurrency);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return connection.prepareStatement(sql,resultSetType,resultSetConcurrency);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return connection.prepareCall(sql,resultSetType,resultSetConcurrency);
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return connection.getTypeMap();
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
        connection.setTypeMap(map);
    }

    @Override
    public void setHoldability(int holdability) throws SQLException {
        connection.setHoldability(holdability);
    }

    @Override
    public int getHoldability() throws SQLException {
        return connection.getHoldability();
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return connection.setSavepoint();
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return connection.setSavepoint(name);
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {
        connection.rollback(savepoint);
    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {
        connection.releaseSavepoint(savepoint);
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return connection.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return connection.prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return connection.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        return connection.prepareStatement(sql,autoGeneratedKeys);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return connection.prepareStatement(sql,columnIndexes);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        return connection.prepareStatement(sql,columnNames);
    }

    @Override
    public Clob createClob() throws SQLException {
        return connection.createClob();
    }

    @Override
    public Blob createBlob() throws SQLException {
        return connection.createBlob();
    }

    @Override
    public NClob createNClob() throws SQLException {
        return connection.createNClob();
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return connection.createSQLXML();
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return connection.isValid(timeout);
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {
        connection.setClientInfo(name,value);
    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {
        connection.setClientInfo(properties);
    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        return connection.getClientInfo(name);
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return connection.getClientInfo();
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return connection.createArrayOf(typeName,elements);
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return connection.createStruct(typeName,attributes);
    }

    @Override
    public void setSchema(String schema) throws SQLException {
        connection.setSchema(schema);
    }

    @Override
    public String getSchema() throws SQLException {
        return connection.getSchema();
    }

    @Override
    public void abort(Executor executor) throws SQLException {
        connection.abort(executor);
    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
        connection.setNetworkTimeout(executor,milliseconds);
    }

    @Override
    public int getNetworkTimeout() throws SQLException {
        return connection.getNetworkTimeout();
    }

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

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

适配器设计模式

在这里插入图片描述

package com.itheima02;

import java.sql.Connection;
import java.util.Collection;
import java.util.List;

/*
    定义一个类,继承适配器类
    定义连接对象和连接池容器对象的成员变量
    通过有参构造为变量赋值
    重写close方法,完成会归还连接
 */
public class MyConnection3 extends MyAdapter{

    private Connection connection;
    private List<Connection> pool;

    public MyConnection3(Connection connection,List<Connection> pool)
    {
        super(connection);
        this.connection=connection;
        this.pool=pool;
    }

    @Override
    public void close()
    {
        pool.add(connection);
    }


}

中间件–适配器

package com.itheima02;

import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/*
    定义一个适配器类,实现Connection接口
    2 定义连接对象的成员变量
    通过有参构造为变量赋值
    重写所有的抽象方法(除了close)
 */
public abstract class MyAdapter implements Connection {

    ///定义连接对象的成员变量
    private Connection connection;
    public MyAdapter(Connection connection)
    {
        this.connection=connection;
    }




    @Override
    public Statement createStatement() throws SQLException {
        return connection.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        return connection.prepareCall(sql);
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return connection.nativeSQL(sql);
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        connection.setAutoCommit(autoCommit);
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return connection.getAutoCommit();
    }

    @Override
    public void commit() throws SQLException {
        connection.commit();
    }

    @Override
    public void rollback() throws SQLException {
        connection.rollback();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return connection.isClosed();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return connection.getMetaData();
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {
        connection.setReadOnly(readOnly);
    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return connection.isReadOnly();
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {
        connection.setCatalog(catalog);
    }

    @Override
    public String getCatalog() throws SQLException {
        return connection.getCatalog();
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {
        connection.setTransactionIsolation(level);
    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return connection.getTransactionIsolation();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return connection.getWarnings();
    }

    @Override
    public void clearWarnings() throws SQLException {
        connection.clearWarnings();
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return connection.createStatement(resultSetType,resultSetConcurrency);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return connection.prepareStatement(sql,resultSetType,resultSetConcurrency);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return connection.prepareCall(sql,resultSetType,resultSetConcurrency);
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return connection.getTypeMap();
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
        connection.setTypeMap(map);
    }

    @Override
    public void setHoldability(int holdability) throws SQLException {
        connection.setHoldability(holdability);
    }

    @Override
    public int getHoldability() throws SQLException {
        return connection.getHoldability();
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return connection.setSavepoint();
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return connection.setSavepoint(name);
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {
        connection.rollback(savepoint);
    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {
        connection.releaseSavepoint(savepoint);
    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return connection.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return connection.prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return connection.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        return connection.prepareStatement(sql,autoGeneratedKeys);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return connection.prepareStatement(sql,columnIndexes);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        return connection.prepareStatement(sql,columnNames);
    }

    @Override
    public Clob createClob() throws SQLException {
        return connection.createClob();
    }

    @Override
    public Blob createBlob() throws SQLException {
        return connection.createBlob();
    }

    @Override
    public NClob createNClob() throws SQLException {
        return connection.createNClob();
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return connection.createSQLXML();
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return connection.isValid(timeout);
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {
        connection.setClientInfo(name,value);
    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {
        connection.setClientInfo(properties);
    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        return connection.getClientInfo(name);
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return connection.getClientInfo();
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return connection.createArrayOf(typeName,elements);
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return connection.createStruct(typeName,attributes);
    }

    @Override
    public void setSchema(String schema) throws SQLException {
        connection.setSchema(schema);
    }

    @Override
    public String getSchema() throws SQLException {
        return connection.getSchema();
    }

    @Override
    public void abort(Executor executor) throws SQLException {
        connection.abort(executor);
    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
        connection.setNetworkTimeout(executor,milliseconds);
    }

    @Override
    public int getNetworkTimeout() throws SQLException {
        return connection.getNetworkTimeout();
    }

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

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

连接池–适配器

package com.itheima01;

import com.itheima.utils.JDBCUtils;
import com.itheima02.MyConnection2;
import com.itheima02.MyConnection3;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

/*
    自定义数据库连接池
 */
public class MyDataSource implements DataSource {
    /// 准备容器,用于保存多个连接对象
    private static List<Connection> pool= Collections.synchronizedList(new ArrayList<>()); /// 线程安全
    /// 定义静态代码块,通过工具类获取10个连接对象
    static
    {
        for (int i=1;i<=10;i++)
        {
            Connection connection = JDBCUtils.getConnection();
            pool.add(connection);
        }
    }

    ///重写getConnection 获取连接对象使用

    @Override
    public Connection getConnection() throws SQLException {
       if(pool.size()>0)
       {
           Connection connection=pool.remove(0);

           ///通过自定义的链接对象,对原有的链接对象进行包装
          // MyConnection2 connection2 = new MyConnection2(connection,pool);
           // return connection2;
           MyConnection3 myConnection3 = new MyConnection3(connection,pool);
           return myConnection3;
       }
       else
       {
           throw new RuntimeException("连接数量用尽");
       }
    }

    /// 定义getSize方法 获取连接池容器的大小
    public int getSize()
    {
        return pool.size();
    }

    @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;
    }
}

动态代理方式–归还连接

在这里插入图片描述

package com.itheima01;

import com.itheima.utils.JDBCUtils;
import com.itheima02.MyConnection2;
import com.itheima02.MyConnection3;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

/*
    自定义数据库连接池
 */
public class MyDataSource implements DataSource {
    /// 准备容器,用于保存多个连接对象
    private static List<Connection> pool= Collections.synchronizedList(new ArrayList<>()); /// 线程安全
    /// 定义静态代码块,通过工具类获取10个连接对象
    static
    {
        for (int i=1;i<=10;i++)
        {
            Connection connection = JDBCUtils.getConnection();
            pool.add(connection);
        }
    }
    /*
        动态代理
     */
    @Override
    public Connection getConnection() throws SQLException {
        if(pool.size()>0)
        {
            Connection connection=pool.remove(0);
            Connection proxyCon = (Connection)Proxy.newProxyInstance(connection.getClass().getClassLoader(), new Class[]{Connection.class},
                    new InvocationHandler(){
                /*
                    执行Connection实现类连接对象所有的方法都会经过invoke
                    如果是close方法就要归还连接
                    如果不是,直接执行连接对象原有的功能即可
                 */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
               if(method.getName().equals("close"))
               {
                   /// 归还连接
                   pool.add(connection);
                   return null;
               }
               else
               {
                   return method.invoke(connection,args);
               }
            }
        });
        return proxyCon;
        }
        else
        {
            throw new RuntimeException("连接数量用尽");
        }
    }

    ///重写getConnection 获取连接对象使用

//    @Override
//    public Connection getConnection() throws SQLException {
//       if(pool.size()>0)
//       {
//           Connection connection=pool.remove(0);
//
//           ///通过自定义的链接对象,对原有的链接对象进行包装
//          // MyConnection2 connection2 = new MyConnection2(connection,pool);
//           // return connection2;
//           MyConnection3 myConnection3 = new MyConnection3(connection,pool);
//           return myConnection3;
//       }
//       else
//       {
//           throw new RuntimeException("连接数量用尽");
//       }
//    }

    /// 定义getSize方法 获取连接池容器的大小
    public int getSize()
    {
        return pool.size();
    }

    @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;
    }
}

动态代理

在这里插入图片描述

package com.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Test {
    public static void main(String[] args) {
        Student student = new Student();
//        student.eat("米饭");
//        student.study();

        /*
            要求:在不改动Student类中如何的代码的前提下,通过Study方法输出一句话
            来黑马学习
            类加载器:和被dialing对象使用的类加载器
            接口类型Class数组:和被代理对象使用相同接口
            代理规则:完成代理增强的功能
         */
        StduentInterface proxyInstance = (StduentInterface) Proxy.newProxyInstance(student.getClass().getClassLoader(), new Class[]{StduentInterface.class}, new InvocationHandler() {
            /*
                执行Student类中所有的方法都会经过invoke方法
                对method方法进行判断 如果是study,则对齐增强
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if(method.getName().equals("study"))
                {
                    System.out.println("来黑马学习");
                    return null;
                }
                else
                {
                    return method.invoke(student,args);
                }
            }
        });

        proxyInstance.eat("米饭");
        proxyInstance.study();
    }
}
package com.proxy;

public class Student implements StduentInterface{
    public void eat(String name)
    {
        System.out.println("学生吃"+name);
    }

    public void study()
    {
        System.out.println("在家学");
    }
}
package com.proxy;

public interface StduentInterface {
    void eat(String name);
    void study();
}

在这里插入图片描述

package com.itheima01;

import com.itheima.utils.JDBCUtils;
import com.itheima02.MyConnection2;
import com.itheima02.MyConnection3;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

/*
    自定义数据库连接池
 */
public class MyDataSource implements DataSource {
    /// 准备容器,用于保存多个连接对象
    private static List<Connection> pool= Collections.synchronizedList(new ArrayList<>()); /// 线程安全
    /// 定义静态代码块,通过工具类获取10个连接对象
    static
    {
        for (int i=1;i<=10;i++)
        {
            Connection connection = JDBCUtils.getConnection();
            pool.add(connection);
        }
    }
    /*
        动态代理
     */
    @Override
    public Connection getConnection() throws SQLException {
        if(pool.size()>0)
        {
            Connection connection=pool.remove(0);
            Connection proxyCon = (Connection)Proxy.newProxyInstance(connection.getClass().getClassLoader(), new Class[]{Connection.class},
                    new InvocationHandler(){
                /*
                    执行Connection实现类连接对象所有的方法都会经过invoke
                    如果是close方法就要归还连接
                    如果不是,直接执行连接对象原有的功能即可
                 */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
               if(method.getName().equals("close"))
               {
                   /// 归还连接
                   pool.add(connection);
                   return null;
               }
               else
               {
                   return method.invoke(connection,args);
               }
            }
        });
        return proxyCon;
        }
        else
        {
            throw new RuntimeException("连接数量用尽");
        }
    }

    ///重写getConnection 获取连接对象使用

//    @Override
//    public Connection getConnection() throws SQLException {
//       if(pool.size()>0)
//       {
//           Connection connection=pool.remove(0);
//
//           ///通过自定义的链接对象,对原有的链接对象进行包装
//          // MyConnection2 connection2 = new MyConnection2(connection,pool);
//           // return connection2;
//           MyConnection3 myConnection3 = new MyConnection3(connection,pool);
//           return myConnection3;
//       }
//       else
//       {
//           throw new RuntimeException("连接数量用尽");
//       }
//    }

    /// 定义getSize方法 获取连接池容器的大小
    public int getSize()
    {
        return pool.size();
    }

    @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;
    }
}

TEST

package com.itheima01;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class MyDataSourceTest  {

    public static void main(String[] args) throws Exception{
        /// 创建连接池对象
        MyDataSource dataSource = new MyDataSource();

        System.out.println("使用之前的数量:"+dataSource.getSize());

        /// 通过连接池对象获取连接对象
        Connection connection =dataSource.getConnection();
        System.out.println(connection.getClass());//class com.mysql.jdbc.JDBC4Connection

        String sql = "select * from student";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next())
        {
            System.out.println(resultSet.getInt("sid")+"\t"+resultSet.getString("name")+
                    "\t"+resultSet.getInt("age")+"\t"+resultSet.getDate("birthday"));
        }

        resultSet.close();
        preparedStatement.close();
        connection.close();

        System.out.println("使用之后的数量:"+dataSource.getSize());
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值