最近整理了一下项目的数据库连接问题,使用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&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();