创建连接池以及对外提供获取连接的方法
private static boolean createConnection(int count) throws Exception { int i = 0; while (connectionPool.size() < maxCount && i < count) { Connection connection = new Connection(); connection.setConnection(DriverManager.getConnection(url, user, password)); connectionPool.add(connection); i++; } return connectionPool.size() < maxCount; } // 对外提供的方法,取得数据库连接 Connection getConnection() throws Exception { for (int i = 0; i < connectionPool.size(); i++) { Connection connection = connectionPool.get(i); if (connection.isUsed()) { continue; } else { return connection; } } // 能走到这里说明已经没有可以用的链接了,所以创建新的链接之后,递归调用自己 if (createConnection(deltaCount)) { return getConnection(); } return null; // 返回null说明数据库连接池已经满了 }下面是有关连接超时的处理,我用一个私有方法处理,用到了之前我做过的工具:滴答滴答(这个工具在我之前的博文里有)(滴答滴答改良版本也可以实现)
private static void scanPool() { new Didadida() { @Override public void doIt() { for (int index = 0; index < connectionPool.size(); index++) { Connection connection = connectionPool.get(index); System.out.println(connection); // 一个连接没有被使用,并且也已经超时 if (!connection.isUsed() && connection.isTimeOut(System.currentTimeMillis(), timeOut)) { if ((connectionPool.size() - 1) >= minCount) { connection.getConnection().close(); connectionPool.remove(connection); } } } } @Override public void beforeDida() { } @Override public void afterStopDida() { } }.setDelayTime(timeOut).start(); } 用另一个类处理连接应该处理的操作(类名称:connection) private java.sql.Connection connection; private boolean isUsed; private long time; // 这个时间用来记录 public Connection() { isUsed = false; } Connection getConnection() { time = System.currentTimeMillis(); isUsed = true; return this; }这里也提供了强制关闭,判断是否连接超时,执行sql语句的方法,一句对于连接的set方法
// 可以超出的时间和当前时间都由外面提供,算出时间差,判断是否为超时连接(超出时间有默认值) void ForceClose(long timeOut, long curTime) { if (!isUsed) { // 如果没有被使用,呢么默认为空闲连接,也就无需关闭 return; } long delayTime = curTime - time; if (timeOut <= delayTime) { isUsed = false; } } // 判断是否超时 boolean isTimeOut(long timeOut, long curTime) { long delayTime = curTime - time; if (timeOut <= delayTime) { return true; } return false; } // 执行sql语句的方法 PreparedStatement preparedStatement(String SQLString) throws SQLException { return connection.prepareStatement(SQLString); } void setConnection(java.sql.Connection connection) { this.connection = connection; }这两个类之间的联系:第二个connection类,是第一个数据库连接池中的list成员,我们用自己写的connection将对数据库的连接封装起来,用于判断是否超时等等