1.为什么要使用连接池
(1)对于开发者而言,通过JDBC获取数据连接,然后执行SQL,是很简单的事情
(2)对于JDBC Driver而言:具体到每一个数据库厂商的驱动实现
- 首先建立应用服务器到数据库服务器之间的连接也就是Socket Connection
- 接下来应用服务器和数据库服务器之间还有很多次数据交换,比如用户密码校验、权限认证等
- 最后数据库应用服务器要初始化连接会话句柄,记录联机日志,并为这一次连接分配进程和系统资源
也就是说:建立一次连接可能花费500毫秒,而你执行一个SQL,很可能只花费50毫秒!!!可以看出来,系统如此忙碌,如果开发者只是执行一个简单的SQL,然后就把此次连接抛弃关闭了,浪费了很多系统资源
2.连接池应该具备什么样的特性
(1)能满足分布式数据源,比如一个应用可能连接多个数据库,或者一个数据库不能的权限
(2)具备事务处理能力,每一个事务独占一个连接来实现,降低事务管理的复杂性
(3)连接池的分配与释放,提高连接的复用度,从而降低建立新连接的开销
(4)连接池的配置与维护,设置最小连接数(minConn)和最大连接数(maxConn)来控制连接池中的连接
3.最基本连接池实现
package com.yli.dal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * 最基本连接池实现,本例使用静态单例,不使用多数据源<br> * 要使用多数据源,将单例改成普通模式即可 * @author yli * */ public class ConnectionPool { private static ConnectionPool pool = null; private String poolName; private String driver; private String url; private String user; private String password; private final static int defaultMin = 5; private final static int defaultMax = 10; private int minConn = defaultMin; private int maxConn = defaultMax; private List<Connection> usedConnections = new ArrayList<Connection>(); private List<Connection> freeConnections = new ArrayList<Connection>(); /** * 私有构造方法,初始化最小连接数 * @param poolName * @param driver * @param url * @param user * @param password * @param minConn * @param maxConn */ private ConnectionPool(String poolName, String driver, String url, String user, String password, int minConn, int maxConn) { this.poolName = poolName; this.driver = driver; this.url = url; this.user = user; this.password = password; this.minConn = minConn; this.maxConn = maxConn; initDriver(); initPool(); } /** * 单例模式,构造连接池,使用默认的最小最大连接数 * @param poolName * @param driver * @param url * @param user * @param password * @return */ public static ConnectionPool newInstanceDefault(String poolName, String driver, String url, String user, String password) { return newInstanceFull(poolName, driver, url, user, password, defaultMin, defaultMax); } /** * 单例模式,构造连接池,指定最小最大连接数 * @param poolName * @param driver * @param url * @param user * @param password * @param minConn * @param maxConn * @return */ public static ConnectionPool newInstanceFull(String poolName, String driver, String url, String user, String password, int minConn, int maxConn) { if (null == pool) { pool = new ConnectionPool(poolName, driver, url, user, password, minConn, maxConn); } return pool; } /** * 获取连接 * @return */ public synchronized Connection getConnection() { Connection conn = null; if (freeConnections.size() > 0) { System.out.println("======================>当前闲置连接数为:[" + freeConnections.size() + "]个"); System.out.println("======================>从闲置连接中获取一个连接"); conn = freeConnections.get(0); freeConnections.remove(0); System.out.println("======================>当前闲置连接减少一个,还剩余[" + freeConnections.size() + "]个"); System.out.println("======================>将获取的闲置连接加入到使用中列表"); usedConnections.add(conn); System.out.println("======================>当前使用中连接数为:[" + usedConnections.size() + "]个"); } else { if (usedConnections.size() >= maxConn) { System.out.println("======================>警告:线程池连接数已经达到最大[" + maxConn + "]个!"); System.out.println("======================>不允许再创建新连接"); } else { System.out.println("======================>当前使用中连接数为:[" + usedConnections.size() + "]个"); System.out.println("======================>已经没有闲置连接,重新创建一个连接"); conn = newConnection(); System.out.println("======================>将新创建的连接状态置为使用中"); usedConnections.add(conn); System.out.println("======================>当前使用中连接数为:[" + freeConnections.size() + "]个"); } } return conn; } /** * 获取连接,指定超时时间 * @param time * @return */ public synchronized Connection getConnection(long time) { Connection conn = null; if (freeConnections.size() > 0) { conn = freeConnections.get(0); freeConnections.remove(0); usedConnections.add(conn); this.notifyAll(); } else { if (usedConnections.size() >= maxConn) { System.out.println("======================>警告:线程池连接数已经达到最大[" + maxConn + "]个!"); System.out.println("======================>不允许再创建新连接"); try { this.wait(time); conn = getConnection(); } catch (InterruptedException e) { e.printStackTrace(); } } else { conn = newConnection(); usedConnections.add(conn); this.notifyAll(); } } return conn; } /** * 释放连接 * * @param conn */ public synchronized void releaseConnection(Connection conn) { System.out.println("======================>释放当前连接"); usedConnections.remove(conn); System.out.println("======================>使用中连接减少一个"); freeConnections.add(conn); System.out.println("======================>闲置连接增加一个"); } /** * 关闭连接:一旦关闭,使用中的连接数应该减少一个 * * @param conn */ public synchronized void closeConnection(Connection conn) { try { if (usedConnections.size() > 0) { usedConnections.remove(conn); } if (null != conn) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭连接池 */ public synchronized void closePool() { System.out.println("======================>开始初关闭连接池"); System.out.println("======================>当前使用中连接数总共有[" + usedConnections.size() + "]个"); clearListConnection(usedConnections); System.out.println("======================>当前闲置连接数总共有[" + freeConnections.size() + "]个"); clearListConnection(freeConnections); System.out.println("======================>关闭连接池成功"); } private void clearListConnection(List<Connection> list) { Connection itemConn; try { for (int i = 0; i < list.size(); i++) { itemConn = list.get(i); list.remove(i); if (null != itemConn) { itemConn.close(); } } } catch (SQLException e) { e.printStackTrace(); } } private void initDriver() { try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void initPool() { System.out.println("======================>开始初始化最少个数连接数"); for (int i = 0; i < minConn; i++) { Connection conn = newConnection(); freeConnections.add(conn); } System.out.println("======================>初始化成功,当前闲置连接数剩余[" + minConn + "]个"); } private Connection newConnection() { Connection conn = null; try { conn = DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); } return conn; } public String getPoolName() { return poolName; } public String getDriver() { return driver; } public String getUrl() { return url; } public String getUser() { return user; } public String getPassword() { return password; } public int getMinConn() { return minConn; } public int getMaxConn() { return maxConn; } }
4.连接池简单测试
package com.yli.dal; import java.sql.Connection; /** * 连接池简单测试 * @author yli * */ public class PoolTest implements Runnable { private ConnectionPool pool; public PoolTest(ConnectionPool pool) { this.pool = pool; } @Override public void run() { Connection conn = pool.getConnection(); // 超时机制获取 // Connection conn = pool.getConnection(200); int threadName = Integer.valueOf(Thread.currentThread().getName()); // 测试释放链接 if (threadName >= 8) { pool.releaseConnection(conn); } } public static void main(String[] args) { String poolName = "MySQL-Connection-Pool"; String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/world"; String user = "root"; String password = "123456"; ConnectionPool pool = ConnectionPool.newInstanceDefault(poolName, driver, url, user, password); System.out.println(); for (int i = 0; i < 20; i++) { PoolTest poolTarget = new PoolTest(pool); new Thread(poolTarget, "" + i).start(); System.out.println(); } try { // 等待5秒再关闭连接池 Thread.sleep(5*1000); pool.closePool(); } catch (InterruptedException e) { e.printStackTrace(); } } }