DBCP连接池简易实现(Oracle)

闲来无事,就看了看连接池,在这里主要讲一下DBCP连接池中的properties配置文件和简单的实现(Oracle数据库)
准备工作:
主要三个jar包:
commons-dbcp2-2.6.0.jar、commons-pool2-2.4.2.jar、commons-logging-1.1.1.jar
之后是properties配置文件
1、Oracle连接的配置文件

driverName=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl 
username=scott
password=a 
//设置是否默认自动提交 默认为true
defaultAutoCommit=true 
//是否为只读 默认为false
defaultReadOnly=false 
//初始化数据池拥有的连接数量
initialSize=10
//池中最多可容纳的可以使用的连接数量
maxActive=20
//最大空闲等待
maxIdle=20
//最小空闲等待
minIdle=5
//最大等待时间
maxWait=20000

2、mysql连接的配置文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/restaurant
username=root
password=a
defaultAutoCommit=true
defaultReadOnly=false
initialSize=30
maxActive=10
maxIdle=10
minIdle=5
maxWait=100
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true

数据库的配置其实都是相同的。
接下来是具体的实现类
DbcpConnection.java

public class DbcpConnection {
	public static DataSource ds = null;
	private static PreparedStatement pstmt=null;
	private static ResultSet rs=null;
	static {
		// 初始化DS就可以提供连接,使用DBCP将初始化
		Properties p = new Properties();// 使用这个工具类来读取文件的数据;
		try {
			p.load(DbcpConnection.class.getClassLoader().getResourceAsStream("dbcpconfig.properties"));
			ds = BasicDataSourceFactory.createDataSource(p);

			((BasicDataSource) ds).setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new ExceptionInInitializerError("初始化错误,请检查配置文件");
		}

	}

	public static Connection getConn() {
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("服务器忙");
		}

	}
  //注意:这里的close关闭是DBCP已经代理过的close()方法并不是原生的close()方法。
	public static void release(ResultSet rs, PreparedStatement pstmt, Connection conn) {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (null != pstmt) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


}

下面是测试类

public class DbcpTest {
	DbHelper db=new DbHelper();	
	Connection conn=null;
	@Test //100个 9051
	public void  DbcpTest01() throws Exception{

		long a=System.currentTimeMillis();
		//for循环测试效率
		for(int i=1;i<1000;i++){
			System.out.println(i);
			conn=DbcpConnection.getConn();
			//close()方法
			conn.close();
		}
		long b=System.currentTimeMillis();
		System.err.println(b-a);
		
		
	}  
	
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值