四大流行的java连接池之BoneCP篇

时间:2023-03-08 18:44:26

BoneCP 是一个开源的快速的 JDBC 连接池。BoneCP很小,只有四十几K(运行时需要log4j和Google Collections的支持,这二者加起来就不小了),而相比之下C3P0 要六百多K。另外个人觉得 BoneCP 有个缺点是,JDBC驱动的加载是在连接池之外的,这样在一些应用服务器的配置上就不够灵活。

Bonecp是一个快速的,免费的,开放源代码的java数据库连接池资源库。

BoneCPConfig类可以用来手动设置连接池及其属性,

Class.forName("org.hsqldb.jdbcDriver");       // load the DB driver
        BoneCPConfig config = new BoneCPConfig();     // create a new configuration object
        config.setJdbcUrl("jdbc:hsqldb:mem:test");    // set the JDBC url
        config.setUsername("sa");                     // set the username
        config.setPassword("");                               // set the password
        
        config.setXXXX(...);                          // (other config options here)
        
        BoneCP connectionPool = new BoneCP(config);   // setup the connection pool
        
        Connection connection;
        connection = connectionPool.getConnection();  // fetch a connection
        
        ...  do something with the connection here ...
        
        connection.close();                           // close the connection
        connectionPool.shutdown();                    // close the connection pool

datasource格式创建连接池,

Class.forName("org.hsqldb.jdbcDriver");       // load the DB driver
        BoneCPDataSource ds = new BoneCPDataSource();  // create a new datasource object
        ds.setJdbcUrl("jdbc:hsqldb:mem:test");                // set the JDBC url
        ds.setUsername("sa");                         // set the username
        ds.setPassword("");                           // set the password
        
        ds.setXXXX(...);                              // (other config options here)
        
        Connection connection;
        connection = ds.getConnection();              // fetch a connection
        
        ...  do something with the connection here ...
        
        connection.close();                           // close the connection
        ds.close();                                   // close the datasource pool

基于spring的代码,

Application Context

 
<!-- BoneCP configuration -->
<bean id="mainDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
   <property name="driverClass" value="com.mysql.jdbc.Driver" />
   <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1/yourdb" />
   <property name="username" value="root"/>
   <property name="password" value="abcdefgh"/>
   <property name="idleConnectionTestPeriod" value="60"/>
   <property name="idleMaxAge" value="240"/>
   <property name="maxConnectionsPerPartition" value="30"/>
   <property name="minConnectionsPerPartition" value="10"/>
   <property name="partitionCount" value="3"/>
   <property name="acquireIncrement" value="5"/>
   <property name="statementsCacheSize" value="100"/>
   <property name="releaseHelperThreads" value="3"/>
</bean>

Code:

Make sure you define theclass below (either via explicit listing of the class name or via<component-scan>.

 
 
@Component
public class Foo {
@Autowired
DataSource ds;
 public void testBoneCP() throws SQLException {
    Connection connection = ds.getConnection();
    System.out.println(connection); // do something with the connection here..
 }
}

基于spring+hibernate的方式

<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean" autowire="autodetect">
        <property name="hibernateProperties">
               <props>
                       <prop key="hibernate.connection.provider_class">com.jolbox.bonecp.provider.BoneCPConnectionProvider</prop>
                       <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
                       <prop key="hibernate.connection.url">jdbc:mysql://127.0.0.1/yourdb</prop>
                       <prop key="hibernate.connection.username">root</prop>
                       <prop key="hibernate.connection.password">abcdefgh</prop>
                       <prop key="bonecp.idleMaxAge">240</prop>
                       <prop key="bonecp.idleConnectionTestPeriod">60</prop>
                       <prop key="bonecp.partitionCount">3</prop>
                       <prop key="bonecp.acquireIncrement">10</prop>
                       <prop key="bonecp.maxConnectionsPerPartition">60</prop>
                       <prop key="bonecp.minConnectionsPerPartition">20</prop>
                       <prop key="bonecp.statementsCacheSize">50</prop>
                       <prop key="bonecp.releaseHelperThreads">3</prop>
               </props>
        </property>
</bean>

基于spring+lazydatasource的方式,

<!-- Hibernate SessionFactory -->
            <bean id="sessionFactory" class="..." autowire="autodetect">
            <!-- Tell hibernate to use our given datasource -->
                <property name="dataSource" ref="dataSource" /> 
            
                <property name="hibernateProperties">
                    <props>
                        <prop key="hibernate.dialect">...</prop>
                        ...
                    </props>
                </property>
            </bean>
            
            <!-- Spring bean configuration. Tell Spring to bounce off BoneCP -->
            <bean id="dataSource"
                class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
                <property name="targetDataSource">
                    <ref local="mainDataSource" />
                </property>
            </bean>
            
            <!-- BoneCP configuration -->
            <bean id="mainDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
                <property name="driverClass" value="com.mysql.jdbc.Driver" />
                <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1/yourdb" />
                <property name="username" value="root"/>
                <property name="password" value="abcdefgh"/>
                <property name="idleConnectionTestPeriod" value="60"/>
                <property name="idleMaxAge" value="240"/>      
                <property name="maxConnectionsPerPartition" value="60"/>
                <property name="minConnectionsPerPartition" value="20"/>
                <property name="partitionCount" value="3"/>
                <property name="acquireIncrement" value="10"/>                              
                <property name="statementsCacheSize" value="50"/>
                <property name="releaseHelperThreads" value="3"/>
            </bean>
            

Jdbc example

The full source code of this example project can befound here:

You will need Apache Maven to automatically includethe required jar files into your classpath. Alternatively you may add therequired JAR files manually.

package com.jolbox;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import com.jolbox.bonecp.BoneCP;

import com.jolbox.bonecp.BoneCPConfig;

/** A test project demonstrating the use of BoneCP in a JDBCenvironment.

* @author wwadge

*

*/

public class ExampleJDBC {

/** Start test

* @param args none expected.

*/

public static voidmain(String[] args) {

BoneCPconnectionPool = null;

Connectionconnection = null;

try {

// load thedatabase driver (make sure this is in your classpath!)

Class.forName("org.hsqldb.jdbcDriver");

} catch (Exceptione) {

e.printStackTrace();

return;

}

try {

// setup theconnection pool

BoneCPConfigconfig = new BoneCPConfig();

config.setJdbcUrl("jdbc:hsqldb:mem:test");// jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb

config.setUsername("sa");

config.setPassword("");

config.setMinConnectionsPerPartition(5);

config.setMaxConnectionsPerPartition(10);

config.setPartitionCount(1);

connectionPool= new BoneCP(config); // setup the connection pool

connection =connectionPool.getConnection(); // fetch a connection

if(connection != null){

System.out.println("Connectionsuccessful!");

Statementstmt = connection.createStatement();

ResultSet rs =stmt.executeQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS");// do something with the connection.

while(rs.next()){

System.out.println(rs.getString(1));// should print out "1"'

}

}

connectionPool.shutdown();// shutdown connection pool.

} catch(SQLException e) {

e.printStackTrace();

} finally {

if(connection != null) {

try{

connection.close();

}catch (SQLException e) {

e.printStackTrace();

}

}

}

}

}

If you use Maven, the following should besufficient to pull in the JAR files required into your classpath:

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.jolbox</groupId>

<artifactId>examplejdbc</artifactId>

<name>Example JDBCProject</name>

<version>1.0.0</version>

<description>ExampleJDBC project</description>

<dependencies>

<dependency>

<groupId>com.jolbox</groupId>

<artifactId>bonecp</artifactId>

<version>0.6.5</version>

<scope>compile</scope>

</dependency>

<!-- This is the HSQLDBdatabase in use by this test. Replace with MySQL, PostgreSQL etc here if youwish. -->

<dependency>

<groupId>hsqldb</groupId>

<artifactId>hsqldb</artifactId>

<version>1.8.0.10</version>

<scope>compile</scope>

</dependency>

</dependencies>

<repositories>

<repository>

<releases>

<enabled>true</enabled>

</releases>

<id>bonecp-repo</id>

<name>BoneCPRepository</name>

<url>http://jolbox.com/bonecp/downloads/maven</url>

</repository>

</repositories>

</project>