import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Stack;
public class DbConnectPool {
private String jdbcDeriver = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://127.0.0.1:3306/";
private String username = "root";
private String password = "201214600";
private String dbname = "game";
private Stack<Connection> freePool;
private ArrayList<Connection> busyPool;
private final int initCount = 10;
private final int maxCount = 80;
private int conCount = 0;
private static final DbConnectPool dcp = new DbConnectPool(); //单例模式
public static DbConnectPool GetInstance(){
//不可实例化,只能通过调用该方法获取连接池对象
return dcp;
}
private DbConnectPool(){
//私有化的构造器
loadDeriver();
freePool = CreatePool();
busyPool = new ArrayList<Connection>();
}
private void loadDeriver(){
//加载数据库驱动
try{
Class.forName(jdbcDeriver) ;
}catch(ClassNotFoundException e){
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace() ;
}
}
private Stack<Connection> CreatePool(){
//创建连接池,连接池用队列表示
Stack<Connection> pool = new Stack<Connection>();
for(int i = 0; i < initCount; i++){
pool.push(createConnection());
}
conCount = initCount;
return pool;
}
private synchronized Connection createConnection(){
//创建一个新的连接
try{
return DriverManager.getConnection(url + dbname + "?user=" + username + "&password=" + password
+ "&useUnicode=true&characterEncoding=gbk&autoReconnect=true&failOverReadOnly=false");
}catch(SQLException se){
System.out.println("数据库连接失败");
se.printStackTrace();
}
return null;
}
public Connection GetConnection() throws SQLException{
//获取空闲连接的方法
if(freePool == null){
return null;
}
Connection con = getFreeConnection();
int waitCount = 0;
while(con == null && waitCount < 5){
waitCount++;
wait(100);
con = getFreeConnection();
}
// System.out.println(conCount + "::" + freePool.size() + "::" + busyPool.size());
return con;
}
private synchronized Connection getFreeConnection() throws SQLException{
//从连接池中获取空闲连接
Connection con = null;
if(freePool.isEmpty()){
if(conCount < maxCount){
con = createConnection();
conCount++;
busyPool.remove(con);
}
}else{
con = freePool.pop();
if(con == null || con.isClosed()){
conCount--;
}else{
busyPool.add(con);
}
}
return con;
}
public synchronized void FreeConnection(Connection con) throws SQLException{
//释放连接
if(con == null){
System.out.println("释放连接为空");
return;
}
busyPool.remove(con);
if(con.isClosed()){
conCount--;
}else{
freePool.push(con);
}
}
private void wait(int mseconds){
try {
Thread.sleep(mseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
MySqlデータベース接続プールのカスタム実装
おすすめ
転載: blog.csdn.net/qq_36382679/article/details/114919898
ランキング