c3p0:参考链接
数据库连接池
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
/**
* @Author shall潇
* @Date 2021/6/1
* @Description
*/
public class MysqlPool {
/*数据库连接池基本配置信息*/
private Integer min = 3; //最小连接数
private Integer max =20; //最大连接数
private Integer increment = 5; //每次增加连接数
private Integer initNum = 5; //初始化连接数
private Byte b = 1; //同步标志
/*下面这段配置信息最好封装一下,这里为了展示代码就写在一起*/
private final String DRIVER = "com.mysql.jdbc.Driver";
private final String URL = "jdbc:mysql://192.168.159.100:3306/bank";
private final String USER = "root";
private final String PASSWORD = "root";
private LinkedList<Connection> connList = new LinkedList<>(); //创建好的连接放在这里
/*当前线程池中的线程数量*/
public int count(){return connList.size();}
/*创建连接---这段代码其实也应该分装好*/
private Connection getConnection(){
Connection connection = null;
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/*生产连接放入线程池*/
private void producerConnection(int num){
for (int i = 0; i < num; i++) {
if(!isCheckedFull()){ //没满就放入
connList.add(getConnection());
}
}
}
/*初始化线程池*/
private MysqlPool(){
producerConnection(initNum);
}
/*判断线程池是否满了*/
private boolean isCheckedFull(){
if(connList.size()>max) return true;
else return false;
}
/*获取连接---外部通过该方法来获取连接对象*/
public Connection getConn(){
synchronized (b) { //考虑并发情况
while (connList.size()==0) {
System.out.println("当前线程池中已无连接,请等待...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (connList.size() < min) { //如果当前线程池中可用线程数低于最低标准,启动子线程创建连接
new Thread(new Runnable() {
@Override
public void run() {
producerConnection(increment);
}
}).start();
}
}
return connList.pop();
}
/*回收连接*/
public void close(Connection connection){
if(null==connection){
return;
}else {
if(isCheckedFull()){ //如果线程池已满,则不回收连接
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else {
connList.push(connection); //未满则回收
}
}
}
//饿汉式
private static MysqlPool instance = null;
static {
instance = new MysqlPool();
}
public static MysqlPool getInstance(){
return instance;
}
public static void main(String[] args) {
MysqlPool instance = getInstance();
for (int i = 0; i < 15; i++) {
Connection conn = instance.getConn();
System.out.println(conn);
}
}
}