package cn.itcast.jdbc.dataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
public class MyDataSource {
private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "123456";
private static int initCount=5;
private static int maxCount=10; //最大连接数,避免创建太多连接影响效率
private int currentCount=0;
public static void main(String[] args) {
}
private LinkedList<Connection> connectionPool = new LinkedList<Connection>(); // 连接池
public MyDataSource() {
try {
for (int i = 0; i < initCount; i++) { // MyDataSource创建时就建立5个连接
this.connectionPool.addLast(this.createConnection());
this.currentCount++;
}
} catch (SQLException e) {
throw new ExceptionInInitializerError();
}
}
public Connection getConnection() throws SQLException {
synchronized (connectionPool) { // 确保多个线程不会取到同一个连接
if (this.connectionPool.size() > 0)
return this.connectionPool.removeFirst();
if(this.currentCount<maxCount){ //当当前连接数小于最大连接数,创建新连接
this.currentCount++;
return this.createConnection();
}
throw new SQLException("已经没有可用连接");
}
}
public void free(Connection conn) { // 释放连接,实际上就是重新加入到连接池
this.connectionPool.addLast(conn);
}
private Connection createConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
}
连接池优化
最新推荐文章于 2025-07-17 20:42:29 发布
本文介绍了一个简单的Java数据库连接池实现方案。通过维护一个连接池,该方案能够在应用程序启动时预先创建一定数量的数据库连接,并在需要时从池中获取空闲连接,使用完毕后将连接放回池中重复利用。这种方式有效减少了频繁创建和销毁连接所带来的资源开销。
7700

被折叠的 条评论
为什么被折叠?



