包括DBCP数据库连接池和C3P0数据库连接池。
DBCP数据库连接池的使用: 方式一:(纯java方式设置参数)
@Test public void dbcpUse() throws SQLException{ BasicDataSource pool = new BasicDataSource(); //连接池 pool.setDriverClassName("com.mysql.jdbc.Driver"); pool.setUrl("jdbc:mysql://127.0.0.1:3306/aa?characterEncoding=utf8&useSSL=true"); pool.setUsername("root"); pool.setPassword("1234"); System.out.println(pool.getMaxActive());//最大连接数 System.out.println(pool.getInitialSize());//初识时连接数 System.out.println(pool.getMaxIdle());//最大空闲时间 System.out.println(pool.getMaxWait());//连接获取最大等待时间 System.out.println("=========================="); for(int i=0;i<16;i++){ Connection con = pool.getConnection(); System.out.println(con.hashCode()); if(i%2==0){ con.close(); } }方式二:(通过读取配置文件生成,注意,下面这种方式配置文件和当前类放在同一个包中)
@Test public void dbcpUseByProperties() throws Exception{ Properties p = new Properties(); p.load(DbcpPoolDemo.class.getResourceAsStream("dbcp.properties")); DataSource pool = BasicDataSourceFactory.createDataSource(p); for(int i=0;i<16;i++){ Connection con = pool.getConnection(); System.out.println(con.hashCode()); if(i%2==0){ con.close(); } } }给DBCP连接池加本地线程管理:
public class DbcpUtil { private static DataSource pool; private static ThreadLocal<Connection> t = new ThreadLocal<Connection>(); static{ Properties p = new Properties(); try { p.load(DbcpUtil.class.getResourceAsStream("dbcp.properties")); pool = BasicDataSourceFactory.createDataSource(p); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public Connection getConnection() throws SQLException{ Connection con = t.get(); if(con==null){ con = pool.getConnection(); t.set(con); } return con; } }