使用apache dbcp连接池

最近整理了一下项目的数据库连接问题,使用apache dbcp连接池:

 

1、配置JNDI数据源:

    在META-INF下新建context.xml,记得是META-INF下,内容

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="jdbc/MySqlPooledDS"    
       auth="Container"   
       type="javax.sql.DataSource"    
       driverClassName="com.mysql.jdbc.Driver"    
       url="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8"    
       username="root"    
       password="root" /> 
</Context>

 

 2、配置连接池

    public static DataSource setupDataSource() throws Exception{
    	
    	// First, we'll need a ObjectPool that serves as the actual pool of connections.
    	GenericObjectPool pool = new GenericObjectPool(null, 100);
    	pool.setMaxIdle(16);
        pool.setMaxWait(5000);
        pool.setMinIdle(8);
        
      
		javax.naming.InitialContext ctx = new javax.naming.InitialContext();
		Context context = (Context) ctx.lookup("java:comp/env");
		DataSource ds = (DataSource) context.lookup("jdbc/MySqlPooledDS");
	    
		// Next, we'll create a ConnectionFactory that the pool will use to create Connections.
		ConnectionFactory connectionFactory = 
			new DataSourceConnectionFactory(ds);
		
		// Now we'll create the PoolableConnectionFactory, 
		// which wraps the "real" Connections created by the ConnectionFactory with
	    // the classes that implement the pooling functionality.
	    PoolableConnectionFactory poolableConnectionFactory = 
	    	new PoolableConnectionFactory(connectionFactory, pool, null, null, false, true);
	    
	    //Finally, we create the PoolingDriver itself, passing in the object pool we created.
	    DataSource dataSource = new PoolingDataSource(pool);
	    
	   return dataSource;
        
    }

  3、利用创建好的连接池取得连接

DataSource dataSource = setupDataSource();
Connection conn = dataSource.getConnection();

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值