为什么使用C3P0:
一般我们在项目中操作数据库时,都是每次需要操作数据库就建立一个连接,操作完成后释放连接。因为jdbc没有保持连接的能力,一旦超过一定时间没有使用(大约几百毫秒),连接就会被自动释放掉。而每次新建连接都需要140毫秒左右的时间,所以耗费时间比较多。若使用C3P0连接池来池化连接,随时取用,则平均每次取用只需要10-20毫秒。这在高并发随机访问数据库的时候对效率的提升有很大帮助。
C3P0连接池会根据你的配置来初始化N个数据库连接,空闲T时间后连接过期又会自动新建K个连接使得连接池总有空闲的数据库连接等待被取用。我们只需通过dataSourse.getConnection()即可从线程池中取用一个已经连接好的空闲连接,执行数据库操作。然后“断开”(放回)这个连接,把这个连接的使用权放回连接池。真正的数据库连接的创建与释放是由C3P0在后台自动完成的,我们花的只是取用与释放占用权的时间。全程耗时10+毫秒,比原来提高了几十倍。
C3P0连接池使用教程
Maven项目导入jar包依赖:
1 2 3 4 5
| <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency>
|
在src目录下新建一个名叫 c3p0-config.xml 的文件,注意,必须是这个文件名。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <named-config name="mysql"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/CoupleSpace</property> <property name="user">root</property> <property name="password">root</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </named-config> ...... </c3p0-config>
|
如何使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class C3p0Utils { static org.apache.log4j.Logger logger=org.apache.log4j.Logger.getLogger(C3p0Utils.class.getName()); static ComboPooledDataSource dataSource=new ComboPooledDataSource("mysql"); public static Connection getConnection(){ try { return dataSource.getConnection(); } catch (Exception e) { logger.error("Exception in C3p0Utils!", e); throw new MyError("数据库连接出错!", e); } } public static void close(Connection conn,PreparedStatement pst,ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { logger.error("Exception in C3p0Utils!", e); throw new MyError("数据库连接关闭出错!", e); } } if(pst!=null){ try { pst.close(); } catch (SQLException e) { logger.error("Exception in C3p0Utils!", e); throw new MyError("数据库连接关闭出错!", e); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { logger.error("Exception in C3p0Utils!", e); throw new MyError("数据库连接关闭出错!", e); } } } }
|