一 連接池概念
數(shù)據(jù)庫連接池負(fù)責(zé)分配槽畔、管理和釋放數(shù)據(jù)庫連接,它允許應(yīng)用程序重復(fù)使用一個(gè)現(xiàn)有的數(shù)據(jù)庫連接,而不是再重新建立一個(gè)试伙;釋放空閑時(shí)間超過最大空閑時(shí)間的數(shù)據(jù)庫連接來避免因?yàn)闆]有釋放數(shù)據(jù)庫連接而引起的數(shù)據(jù)庫連接遺漏田绑。這項(xiàng)技術(shù)能明顯提高對(duì)數(shù)據(jù)庫操作的性能勤哗。
二 思路
- 指定初始化連接數(shù)目程序啟動(dòng)時(shí)就執(zhí)行創(chuàng)建
- 指定最大連接數(shù)目
- 指定當(dāng)前使用連接數(shù)目
三 實(shí)現(xiàn)過程
- 指定全局變量:初始化數(shù)目,最大連接數(shù)掩驱,當(dāng)前連接數(shù)芒划,連接池集合
- 構(gòu)造函數(shù):循環(huán)創(chuàng)建 “初始化數(shù)目” 連接
- 數(shù)據(jù)庫連接方法
- 獲取連接
- 池中有連接,直接拿
- 池中沒有連接欧穴,判斷是否達(dá)到做大連接數(shù);達(dá)到民逼,拋出異常;沒有達(dá)到最大連接數(shù)涮帘,創(chuàng)建新的連接
- 釋放和連接(連接放回集合中)
四 代碼
package utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;
/**
* Created by pc on 2017/9/10.
*/
public class MyConnectionPool {
int init_count = 3; //初始化鏈接數(shù)目
int max_count = 10; //最大鏈接數(shù)
int current_count = 0; //記錄當(dāng)前使用的鏈接數(shù)
//連接池:存放所有的初始化鏈接
public LinkedList<Connection> pool = new LinkedList<Connection>();
//1.構(gòu)造函數(shù)缴挖,初始化連接放入連接池
public MyConnectionPool(){
for (int i = 0;i < init_count;i++){
current_count++;//記錄當(dāng)前連接數(shù)
//把鏈接加到連接池
pool.addLast(creatConnection());
}
}
//2.創(chuàng)建一個(gè)新的鏈接方法
public Connection creatConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");//加載驅(qū)動(dòng)
String url = "jdbc:mysql://localhost:3306/test";//加載數(shù)據(jù)庫鏈接
String user = "root";//配置用戶名
String password = "root";//配置密碼
return DriverManager.getConnection(url,user,password);//獲取鏈接
}catch (Exception e){
throw new RuntimeException(e);
}
}
//3.獲取鏈接
public Connection getConnection(){
//池中有鏈接直接拿
if (pool.size() > 0){
return pool.removeFirst();//將第一個(gè)list集合刪除并返回
}
//池中沒有鏈接,判斷是否達(dá)到最大連接數(shù)焚辅;如果沒有映屋,創(chuàng)建新的鏈接
if (current_count < max_count){
//記錄當(dāng)前使用的連接數(shù)
current_count++;
//創(chuàng)建鏈接
return creatConnection();
}
//達(dá)到最大鏈接,拋出異常
throw new RuntimeException("當(dāng)前已經(jīng)達(dá)到最大連接數(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 (Exception e){
throw new RuntimeException(e);
}
}
}
}