栏目:缓存设计 作者:admin 日期:2015-03-08 评论:0 点击: 2,488 次
(1)新建配置文件:c3p0.properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#驱动 c3p0.driverClass=com.mysql.jdbc.Driver #地址 c3p0.jdbcUrl=jdbc:mysql://localhost:3306/jdbc #用户名 c3p0.user=root #密码 c3p0.password=lovejava #------------------------------- #连接池初始化时创建的连接数 c3p0.initialPoolSize=3 #连接池保持的最小连接数 c3p0.minPoolSize=3 #连接池在无空闲连接可用时一次性创建的新数据库连接数,default:3 c3p0.acquireIncrement=3 #连接池中拥有的最大连接数,如果获得新连接时会使连接总数超过这个值则不会再获取新连接,而是等待其他连接释放,所以这个值有可能会设计地很大,default : 15 c3p0.maxPoolSize=15 #连接的最大空闲时间,如果超过这个时间,某个数据库连接还没有被使用,则会断开掉这个连接,单位秒 c3p0.maxIdleTime=100 #连接池在获得新连接失败时重试的次数,如果小于等于0则无限重试直至连接获得成功 c3p0.acquireRetryAttempts=30 #连接池在获得新连接时的间隔时间 c3p0.acquireRetryDelay=1000 |
(2)连接池类ConnectionPool
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 |
package com.study.pool; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class ConnectionPool { private DataSource ds; private static ConnectionPool pool; private ConnectionPool(){ ds = new ComboPooledDataSource(); } public static final ConnectionPool getInstance(){ if(pool==null){ try{ pool = new ConnectionPool(); }catch (Exception e) { e.printStackTrace(); } } return pool; } public synchronized final Connection getConnection() { try { return ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return null; } } |
(3)PoolThread类
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 |
package com.study.pool; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class PoolThread extends Thread { @Override public void run(){ ConnectionPool pool = ConnectionPool.getInstance(); Connection con = null; PreparedStatement stmt= null; ResultSet rs = null; try{ con = pool.getConnection(); stmt = con.prepareStatement("select sysdate as nowtime from dual"); rs = stmt.executeQuery(); while(rs.next()){ System.out.println(Thread.currentThread().getId()+"---------------开始"+rs.getString("nowtime")); } } catch (Exception e) { e.printStackTrace(); }finally{ try { rs.close(); stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getId()+"--------结束"); } } |
(4)PoolMain类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.study.pool; public class PoolMain { /** * 数据源缓冲池 实例练习 */ public static void main(String[] args) { System.out.println("缓冲池模拟开始"); PoolThread[] threads = new PoolThread[50]; for(int i=0;i < threads.length;i++) { threads[i] = new PoolThread(); } for(int i=0;i < threads.length;i++) { threads[i].start(); } } } |
------====== 本站公告 ======------
金丝燕网,一个严谨的网站!