自定义连接池 用代码读写全过程

package 连接池;

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

public class MyConnection implements Connection {

    private  MyDateSource myDateSource;
    private Connection connection;

    public  MyConnection(MyDateSource myDateSource,Connection connection){
        this.myDateSource=myDateSource;
        this.connection=connection;

    }
    @Override
    public void close() throws SQLException {
    //把连接从工作连接池放回空闲连接池
        if(myDateSource.getIdlePoll().size()<myDateSource.getMaxActive()){
             myDateSource.getWorkPool().remove(this);
            myDateSource.getIdlePoll().addLast(this);
        }
    }

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

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

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

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

package 连接池;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;

public class MyDateSource extends MyAdstractDataSource{
     //工作连接池
    private LinkedList<MyConnection> workPool=new LinkedList<>();

    //空闲连接池
    private LinkedList<MyConnection> idlePoll=new LinkedList<>();

    public LinkedList<MyConnection> getWorkPool() {
        return workPool;
    }
   private  boolean initFlag=false;


    public LinkedList<MyConnection> getIdlePoll() {
        return idlePoll;
    }

    public MyDateSource(){

    }
    //TODO 从工作连接池获取一个连接
    @Override
    public Connection getConnection() throws SQLException {
        MyConnection connection=null;
        this.init();
        //如果空闲连接不为空就直接取
        if(!idlePoll.isEmpty()){
            connection=idlePoll.removeFirst();
        }else{
            //如果工作连接数小于最大连接数就创建一个
            if(workPool.size()<super.getMaxActive()){
                connection =new MyConnection(this,super.getConnection());
            }
        }
        //连接不为空添加到工作连接
        if(connection!=null){
            workPool.addLast(connection);
        }
        return connection;
    }

    public  void init() throws SQLException {
        //初始化十个连接
        if(!initFlag==false){
        while (idlePoll.size()<super.getInitialSize()) {
            idlePoll.add(new MyConnection(this, super.getConnection()));


        }
        initFlag=true;
        }
    }
}

package 连接池;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

public abstract class MyAdstractDataSource implements DataSource  {
      private  String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public int getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(int initialSize) {
        this.initialSize = initialSize;
    }

    public int getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }

    public boolean isInitFlag() {
        return initFlag;
    }

    public void setInitFlag(boolean initFlag) {
        this.initFlag = initFlag;
    }

    private  String username;
      private  String password;
      private  String driverClassName;
      //初始连接数
      private int initialSize=10;
      private  int maxActive=30;

       private  boolean initFlag=false;

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

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

    private  Connection doDetConnection(String username,String password) throws SQLException{
        if(!initFlag){
            try {
                Class.forName(driverClassName);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            initFlag=true;
        }
        return DriverManager.getConnection(url,username,password);
    }




    @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 连接池;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TestMyDataSource {
    public  static  String url="jdbc:mysql://localhost:3306/java001?useServerPrepStmts=true";
    public static String username="root";
    public static String password="root";
    public static String driverClassName="com.mysql.cj.jdbc.Driver";
  @Test
    public  void testMyDataSource() throws SQLException {
     MyDateSource myDateSource=new MyDateSource();

     myDateSource.setDriverClassName(driverClassName);
     myDateSource.setUrl(url);
     myDateSource.setUsername(username);
     myDateSource.setPassword(password);
     long statr=System.currentTimeMillis();
        for (int i = 0; i <500 ; i++) {
            Connection connection=myDateSource.getConnection();
            connection.close();
        }
        long end=System.currentTimeMillis();
        System.out.println(""+(end-statr)+"ms");



        statr=System.currentTimeMillis();
      for (int i = 0; i <500 ; i++) {
          Connection connection= DriverManager.getConnection(url,username,password);
          connection.close();
      }
end=System.currentTimeMillis();
      System.out.println(""+(end-statr)+"ms");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值