Java BoneCP JDBC连接池

package com.hh.util;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

/**
 * 
 * 项目名称(Project name):MySQLConnectonPool
 * <p>
 * 包 名 (Package name):com.lixunhui.util
 * <p>
 * 类 名 (Class name):ConnectionPool
 * <p>
 * 类描述(Description):
 * <p>
 * 作 者 (Author) :[email protected]
 * <p>
 * 创建时间(Create Date):2013-3-30 下午1:58:35
 * <p>
 * 修改人:hh
 * <p>
 * 修改时间:2013-3-30 下午1:58:35
 * <p>
 * 修改备注:
 * <p>
 * 版 本 (Version): @version 1.0
 */
public class ConnectionPool {
	static Logger log=Logger.getLogger(ConnectionPool.class);
	private static BoneCP connectionPool;
	/**
	 * 从连接池中获取Connection
	 * 
	 * @Author [email protected]
	 * @Description
	 * @return
	 */
	
	public static Connection getConnection() {
		Connection connection = null;
		int totalConnection=0;
		int freeConnection=0;
		int busyConnection=0;
		
		if(null==connectionPool){
			log.debug("数据库连接池不存在,新建连接池并从中获取数据库链接");
			String username = ResourcesProp.getValue("username");
			String password = ResourcesProp.getValue("password");
			String url = ResourcesProp.getValue("url");
			String driver = ResourcesProp.getValue("driver");
			try {
				Class.forName(driver);
				BoneCPConfig config = new BoneCPConfig();
				// 设置URL
				config.setJdbcUrl(url);
				// 设置用户名
				config.setUsername(username);
				// 设置密码
				config.setPassword(password);
				// 设置60秒检索一次数据库的空暇连接数
				config.setIdleConnectionTestPeriod(60);
				// 设置余暇链接时候
				config.setIdleMaxAge(240);
				// 设置每个分区中最大连接数
				config.setMaxConnectionsPerPartition(100);
				// 设置每个分区中最小链接数
				config.setMinConnectionsPerPartition(5);
				// 当链接用尽的时候,一次获取多少个连接数
				config.setAcquireIncrement(5);
				config.setReleaseHelperThreads(10);
				config.setPartitionCount(3);
				connectionPool = new BoneCP(config);
				connection = connectionPool.getConnection();
				totalConnection=connectionPool.getTotalCreatedConnections();
				freeConnection=connectionPool.getTotalFree();
				busyConnection=connectionPool.getTotalLeased();
				log.debug("从数据库连接池中获取连接成功,总链接数"+totalConnection+"空闲连接数"
						+freeConnection+"总占用"+busyConnection);
			} catch (Exception e) {
				log.error("从新建数据库连接池中获取链接失败,总链接数"+totalConnection+"空闲连接数"
						+freeConnection+"总占用"+busyConnection, e);
				e.printStackTrace();
			}
		}else{
			log.debug("数据库连接池存在,从连接池中获取数据库链接");
			try {
				connection=connectionPool.getConnection();
				totalConnection=connectionPool.getTotalCreatedConnections();
				freeConnection=connectionPool.getTotalFree();
				busyConnection=connectionPool.getTotalLeased();
				log.debug("从数据库连接池中获取链接成功,总链接数"+totalConnection+"空闲连接数"
						+freeConnection+"总占用"+busyConnection);
			} catch (SQLException e) {
				log.error("从数据库链接池中获取链接失败",e);
				e.printStackTrace();
			}
		}
		return connection;
	}
}

你可能感兴趣的:(java,连接池,bonecp)