赞
踩
package lm; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class ConfigFile { static public Properties p = new Properties(); private static ConfigFile singleton = null; static public ConfigFile getInstance() { if (singleton == null) { synchronized(ConfigFile.class) { if (singleton == null) { singleton = new ConfigFile(); } } } return singleton; } public void init(String path) throws FileNotFoundException, IOException { p.load(new FileInputStream(path)); } public String getMysqlUrl() { return p.getProperty("MYSQL_URL"); } public String getMYSQL_USER() { return p.getProperty("MYSQL_USER"); } public String getMYSQL_PWD() { return p.getProperty("MYSQL_PWD"); } }
package lm; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import up.conf.ConfigFile; public class ConnectionPool { Logger LOG = LogManager.getLogger(ConnectionPool.class); static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String JDBC_DB_URL = ConfigFile.getInstance().getMysqlUrl(); String JDBC_USER = ConfigFile.getInstance().getMYSQL_USER(); String JDBC_PASS = ConfigFile.getInstance().getMYSQL_PWD(); List<Connection> cs = new ArrayList<Connection>(); private static ConnectionPool singleton = null; int size; static public ConnectionPool getInstance() { if (singleton == null) { synchronized(ConnectionPool.class) { if (singleton == null) { singleton = new ConnectionPool(10); } } } return singleton; } private ConnectionPool(int size) { this.size = size; init(); } public void init() { // 这里恰恰不能使用try-with-resource的方式,因为这些连接都需要是"活"的,不要被自动关闭了 try { Class.forName(JDBC_DRIVER); for (int i = 0; i < size; i++) { Connection c = DriverManager.getConnection(JDBC_DB_URL,JDBC_USER, JDBC_PASS); // System.out.println("完成第"+ ( i + 1 ) +"个连接"); cs.add(c); } } catch (ClassNotFoundException e) { LOG.error("init connectPool: ",e); //System.out.println("init connectPool: " + e.getMessage()); } catch (SQLException e) { LOG.error("init connectPool: ",e); //System.out.println("init connectPool: " + e.getMessage()); } } public synchronized Connection getConnection() { while (cs.isEmpty()) { try { // 如果连接池中没有连接可用则等待 this.wait(); } catch (InterruptedException e) { //System.out.println("getConnection get error:" + e.getMessage()); LOG.error("getConnection get error:",e); } } // 移除第一个连接池 Connection conn = cs.remove(0); return conn; } public synchronized void returnConnection(Connection c) { // 使用完给回连接池中 cs.add(c); // 唤醒wait告诉它有新的连接池可用 this.notifyAll(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。