Java实现数据库连接池例子

来源:互联网 发布:淘宝开店招牌素材 编辑:程序博客网 时间:2024/06/05 02:00

Java实现数据库连接池例子

======================


ConnectionPoolUtil.java

package com.util;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.SQLException;import java.util.Properties;import org.apache.commons.dbcp.BasicDataSource;import org.apache.log4j.Logger;public class ConnectionPoolUtil {private static ConnectionPoolUtil cpu;private BasicDataSource dataSource;private boolean autoCommit = false;private String dbHost;private String dbPort;private String dbName;public static ConnectionPoolUtil getInstance(){if(null == cpu){cpu = new ConnectionPoolUtil();}return cpu;}private ConnectionPoolUtil(){}// class文件根目录private String classPath = PathUtil.getClassPath();private Properties read(String name) throws IOException {InputStream in = new BufferedInputStream(new FileInputStream(classPath+ name));Properties p = new Properties();p.load(in);return p;}public Connection getConnection() throws SQLException{if(null==dataSource){initPool();}Connection conn = dataSource.getConnection();dataSource.getNumActive();conn.setAutoCommit(autoCommit);return conn;}private void initPool() {try {if(null != this.dataSource&&this.dataSource.getConnection() != null){return ;}} catch (SQLException e1) {e1.printStackTrace();}Properties dbProps = null;Logger log = Logger.getLogger(this.getClass());// 下面的读取配置文件可以根据实际的不同修改try {dbProps = read("properties/Application.properties");String driveClassName = dbProps.containsKey("jdbc.driverClassName")?dbProps.getProperty("jdbc.driverClassName"):"oracle.jdbc.driver.OracleDriver";String url = dbProps.getProperty("jdbc.url");if(url.split("@").length==2&&url.split("@")[1].split(":").length==3){dbHost = url.split("@")[1].split(":")[0];dbPort = url.split("@")[1].split(":")[1];dbName = url.split("@")[1].split(":")[2];}String username = dbProps.getProperty("jdbc.username");String password = dbProps.getProperty("jdbc.password");String initialSize = dbProps.getProperty("dataSource.initialSize");String minIdle = dbProps.containsKey("dataSource.minIdle")?dbProps.getProperty("dataSource.minIdle"):"5";String maxIdle = dbProps.containsKey("dataSource.maxIdle")?dbProps.getProperty("dataSource.maxIdle"):"20";String maxWait = dbProps.containsKey("dataSource.maxWait")?dbProps.getProperty("dataSource.maxWait"):"120000";String maxActive = dbProps.containsKey("dataSource.maxActive")?dbProps.getProperty("dataSource.maxActive"):"80";autoCommit = Boolean.getBoolean(dbProps.containsKey("conn.autoCommit")?dbProps.getProperty("conn.autoCommit"):"false");// 是否在自动回收超时连接的时候打印连接的超时错误boolean logAbandoned = (Boolean.valueOf(dbProps.getProperty("dataSource.logAbandoned", "false"))).booleanValue();// 是否自动回收超时连接boolean removeAbandoned = (Boolean.valueOf(dbProps.getProperty("dataSource.removeAbandoned", "false"))).booleanValue();// 超时时间(以秒数为单位)int removeAbandonedTimeout = Integer.parseInt(dbProps.getProperty("dataSource.removeAbandonedTimeout", "300"));dataSource = new BasicDataSource();dataSource.setDriverClassName(driveClassName);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);// 初始化连接数if (initialSize != null)dataSource.setInitialSize(Integer.parseInt(initialSize));// 最小空闲连接if (minIdle != null)dataSource.setMinIdle(Integer.parseInt(minIdle));// 最大空闲连接if (maxIdle != null)dataSource.setMaxIdle(Integer.parseInt(maxIdle));// 超时回收时间(以毫秒为单位)if (maxWait != null)dataSource.setMaxWait(Long.parseLong(maxWait));// 最大连接数if (maxActive != null) {if (!maxActive.trim().equals("0"))dataSource.setMaxActive(Integer.parseInt(maxActive));}dataSource.setLogAbandoned(logAbandoned);dataSource.setRemoveAbandoned(removeAbandoned);dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);Connection conn = dataSource.getConnection();if (conn == null) {log.error("无法从连接池中取得连接!检查设置!!!");} else {conn.close();}log.info("连接池创建成功!!!");} catch (IOException e) {log.error("无法找到连接池配置");} catch (Exception e) {log.error("创建连接池失败!请检查设置!!!");}}public int getConns(){if(dataSource==null){return 0;}else{return dataSource.getNumActive();}}public String getDbHost() {return dbHost;}public String getDbPort() {return dbPort;}public String getDbName() {return dbName;}}


获取连接:

public class BaseDao {    private static final Logger logger = Logger.getLogger(BaseDao.class.getName());    protected RequestContext requestContext;    private ConnectionPoolUtil connectionPoolUtil;    protected ActionMessages errors = new ActionMessages();    public BaseDao(RequestContext requestContext) {        this.requestContext = requestContext;        //databaseManager = DatabaseManager.getInstance();        connectionPoolUtil = ConnectionPoolUtil.getInstance();    }    public Connection getConnection() throws DatabaseException {    Connection connection = null;    try{    connection = connectionPoolUtil.getConnection();    }catch(Exception exception){    exception.printStackTrace();    }        return connection;    }
}






0 0
原创粉丝点击