參考手寫數據庫連接池

1、配置文件

public class DbBean { private String driverName="com.mysql.jdbc.Driver";

private String url="jdbc:mysql://localhost:3306/test";

private String admin="root";

private String password="123456";

private String poolName="pool1";

private int minConnections=1;//最小空閒線程數
private int maxConnection=10;//最大空閒線程數

private int initConnections=5;//初始化線程數

private int maxActiveConnections=100;//最大活動線程連接數

private long connTimeOut=1000;//重複獲得連接的頻率

private long connectionTimeOut=1000*60*20;//連接超時時間


public String getDriverName() {
    return driverName;
}

public void setDriverName(String driverName) {
    this.driverName = driverName;
}

public String getUrl() {
    return url;
}

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

public String getAdmin() {
    return admin;
}

public void setAdmin(String admin) {
    this.admin = admin;
}

public String getPassword() {
    return password;
}

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

public String getPoolName() {
    return poolName;
}

public void setPoolName(String poolName) {
    this.poolName = poolName;
}

public int getMinConnections() {
    return minConnections;
}

public void setMinConnections(int minConnections) {
    this.minConnections = minConnections;
}

public int getMaxConnection() {
    return maxConnection;
}

public void setMaxConnection(int maxConnection) {
    this.maxConnection = maxConnection;
}

public int getInitConnections() {
    return initConnections;
}

public void setInitConnections(int initConnections) {
    this.initConnections = initConnections;
}

public int getMaxActiveConnections() {
    return maxActiveConnections;
}

public void setMaxActiveConnections(int maxActiveConnections) {
    this.maxActiveConnections = maxActiveConnections;
}

public long getConnTimeOut() {
    return connTimeOut;
}

public void setConnTimeOut(long connTimeOut) {
    this.connTimeOut = connTimeOut;
}

public long getConnectionTimeOut() {
    return connectionTimeOut;
}

public void setConnectionTimeOut(long connectionTimeOut) {
    this.connectionTimeOut = connectionTimeOut;
}

}

public interface DbPool {

 Connection getConnection() throws InterruptedException;
void releaseConnection(Connection connection);

}

public class DbPoolImpl implements DbPool {

/**
 * 空閒連接池
 */
private  LinkedBlockingQueue<Connection> idleConnectPool=new LinkedBlockingQueue<Connection>();

/**
 * 活躍連接池
 */
private  LinkedBlockingQueue<Connection> busyConnectPool=new LinkedBlockingQueue<Connection>();

/**
 * 當前正在被使用的連接數
 */
private AtomicInteger activeSize = new AtomicInteger(0);

private DbBean dbBean;

DbPoolImpl(DbBean dbBean){
    this.dbBean =dbBean;
    init();


}

public void init() {

    int initSize = dbBean.getInitConnections();
    if(dbBean==null) {
         return;
     }

    for (int i = 0; i <initSize ; i++) {
         Connection connection =createConnection();
         if(createConnection()!=null){
             idleConnectPool.add(connection);
         }
    }
}
//獲取連接
public synchronized Connection getConnection() {
    Connection connection=null;
    try{
        if(activeSize.get()<dbBean.getMaxActiveConnections()){
            if(idleConnectPool.size()>0){
                connection = idleConnectPool.remove();

            }else {
                connection = createConnection();
            }

            if(isAvailable(connection)){
                busyConnectPool.add(connection);
            }else {
                activeSize.getAndDecrement();
                connection=getConnection();
            }

        }else {
            //大於最大活動線程數
            wait(dbBean.getConnTimeOut());
            connection= getConnection();
        }

    }catch (Exception e){
    }

    return connection;
}

public boolean isAvailable(Connection connection){
    try {
        if(connection==null||connection.isClosed()){
            return false;
        }else{
            return true;
        }
    }catch (Exception e){
        return false;
    }
}

public  void releaseConnection(Connection connection) {
    try{
        if(connection==null || connection.isClosed()) {
            return;
        }else {
           if(isAvailable(connection)){
               if(idleConnectPool.size()<dbBean.getMaxConnection()){
                   idleConnectPool.add(connection);
               }else{
                   connection.close();
               }

               busyConnectPool.poll();
               activeSize.getAndDecrement();
               notifyAll();

           }
        }

    }catch (Exception e){

    }


}

public Connection createConnection(){

  Connection connection=null;
  try {
      String driverName = dbBean.getDriverName();
      Class.forName(driverName);
      connection = DriverManager.getConnection(dbBean.getUrl(), dbBean.getAdmin(), dbBean.getPassword());
      if(connection!=null){
         activeSize.getAndIncrement();
       return connection;
      }

  }catch (Exception e) {
      System.out.println(e);
  }
  return connection;

} }

public class TestMain {

public static void main(String[] args) {
    ThreadConnection threadConnection =new ThreadConnection();
    for (int i = 0; i <3; i++) {
        Thread thread = new Thread(threadConnection, "線程" + i);
        thread.start();
    }

}

}

class ThreadConnection implements Runnable{

public void run() {
    for (int i = 0; i <10 ; i++) {
        try {
            Connection connection = ConnPoolManager.getConnection();
            System.out.println("i==="+i+"==="+Thread.currentThread().getName()+"connnection:"+connection);
            ConnPoolManager.releaseConnection(connection);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}

參考: https://www.bilibili.com/video/BV1Bk4y167AX?p=8

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章