1、数据库连接配置c3p0.properties:
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc\:mysql\://localhost\:3306/mybatis
c3p0.user=root
c3p0.password=root
#-------------------------------
#连接池初始化时创建的连接数
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
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
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 name from items");
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(Thread.currentThread().getId()
+ "---------------开始" + rs.getString("name"));
}
} 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
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();
}
}
}