BoneCP纯Java实现的数据库连接池
正好在项目中有个小应用可以测试一下,代码如下:
下载bonecp-0.7.0.jar,官方下载后是一个bonecp-0.7.0.jar.zip文件,直接将.zip删掉即可
bonecp依赖其它两个包,一个slf4j(Log),另一个是guava-r07.jar(google collection)
Requirements(官方说明)
- A database that accepts connections
- A driver to go with it
- Google Collections library, available for free from here. Maven users should get this automatically during their builds.
- The SLF4J logging library. Older versions of BoneCP use Log4J library directly.
- JDK1.5 or higher.
slf4j中仅需要slf4j-api-1.6.1.jar和slf4j-nop-1.6.1.jar两个jar
创建连接的公共类
mport com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author ZHOUKAI
*/
public class ConnectionPool {
private static BoneCP boneCp;
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private ConnectionPool() {
try {
// 初始化连接池
BoneCPConfig boneConf = new BoneCPConfig();
// 数据库URL连接
boneConf.setJdbcUrl("url");
// 设置数据库连接用户名
boneConf.setUsername("u");
// 设置数据库连接密码
boneConf.setPassword("p");
// 设置连接池在每个分区中的最大连接数
boneConf.setMaxConnectionsPerPartition(30);
// 设置连接池设在每个分区中的最小连接数
boneConf.setMinConnectionsPerPartition(5);
// 连接释放处理
boneConf.setReleaseHelperThreads(3);
// 当连接池中的连接耗尽的时候 BoneCP一次同时获取的连接数
boneConf.setAcquireIncrement(5);
// 设置分区(设置 3个分区)
boneConf.setPartitionCount(2);
// 设置连接空闲时间(分钟)
boneConf.setIdleMaxAge(30);
// 每120秒检查所有连接池中的空闲连接
boneConf.setIdleConnectionTestPeriod(120);
boneCp = new BoneCP(boneConf);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static class SingletonHolder {
static ConnectionPool instance = new ConnectionPool();
}
public static ConnectionPool getInstance() {
return SingletonHolder.instance;
}
public Connection getConnection() throws SQLException {
return boneCp.getConnection();
}
}