一.自定義連接池
實現(xiàn)思路
1.指定初始化連接數(shù)目浩淘,程序啟動時就執(zhí)行創(chuàng)建
2.指定最大連接數(shù)
3.指定當前使用的連接數(shù)(不能超過最大連接數(shù))
代碼實現(xiàn):
1.連接池類
2.指定全局參數(shù):初始化數(shù)目店归,最大連接數(shù)凶硅,當前連接,連接池集合
3.構(gòu)造函數(shù):循環(huán)創(chuàng)建三個連接
4.寫一個創(chuàng)建連接的方法
5.獲取連接
判斷:
--池中有連接震庭,直接拿
--池中沒有連接鼻由,判斷是否達到做大連接數(shù);達到,拋出異常橱赠;沒有達到最大連接數(shù)尤仍,創(chuàng)建新的連接
6.釋放連接
連接放回集和中
自定義連接池
1.創(chuàng)建連接池中3個Connection連接
2.最大連接數(shù)6個
public class MyConnectionPool {
private int init_count = 3;//初始化鏈接數(shù)目
private int max_count = 6;//最大連接數(shù)
private int current_count = 0;//記錄當前使用的連接數(shù)
//連接池:存放所有的初始化連接
private LinkedList<Connection> pool = new LinkedList<Connection>();
//1.構(gòu)造函數(shù),初始化連接放入連接池
public MyConnectionPool() {
for (int i = 0; i < init_count; i++) {
current_count++;//記錄當前連接數(shù)
//把連接加到連接池
pool.addLast(creatConnection());
}
}
//2.創(chuàng)建一個新的連接方法
private Connection creatConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/car";//2.指定連接數(shù)據(jù)庫的地址名稱
String user="root";
String passWord = "root";//指定用戶名和密碼
return DriverManager.getConnection(url,user,passWord);//3獲取數(shù)據(jù)庫連接
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//3.獲取連接
public Connection getConnection() {
//池中有連接狭姨,直接拿
if (pool.size() > 0) {
return pool.removeFirst();//將第一個list集合刪除并返回
}
//池中沒有連接宰啦,判斷是否達到做大連接數(shù);沒有達到最大連接數(shù),創(chuàng)建新的連接
if (current_count < max_count) {
//記錄當前使用的連接數(shù)
current_count++;
//創(chuàng)建連接
return creatConnection();
}
//達到最大連接數(shù)饼拍,拋出異常赡模;
throw new RuntimeException("當前已經(jīng)達到最大連接數(shù)");
}
//4.釋放連接
public void realeaseConnection(Connection conn){
//判斷:連接池中數(shù)目如果小于初始化連接,就放入池中
if(pool.size()<init_count){
pool.addLast(conn);
}else{
try {
//關(guān)閉連接
current_count--;
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
-
測試
//測試連接
public static void main(String[] args){
MyConnectionPool pool = new MyConnectionPool();
System.out.println("連接池:"+pool.current_count);
Connection conn1 = pool.getConnection();
pool.getConnection();
pool.getConnection();
pool.getConnection();
pool.getConnection();
pool.getConnection();
pool.realeaseConnection(conn1);
pool.getConnection();
System.out.println("當前連接池中:"+pool.pool.size());
System.out.println("當前連接:"+pool.current_count);
}