Java实现数据库连接池例子

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;
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值