1. 程式人生 > >Java中的BoneCP資料庫連線池

Java中的BoneCP資料庫連線池

最近在學習公司的框架,涉及到連線資料庫部分的技術時,發現用的是BoneCP,上網查閱了相關資料與例子,個人覺得下面這例子比較容易懂,有收藏的價值存在,故將其放在自己的部落格裡,供學習時參考: 

BoneCP is a fast, free, open-source, Java database connectionpool (JDBC Pool) library. If you are familiar with C3P0 and DBCPthen you already know what this means. For the rest, this is alibrary that will manage a database connection for you to getfaster database access in your application.
BoneCP is fast! For some tests, it's almost 25 times faster thanthe next fastest connection pool option, not to mention that BoneCPnever spin-locks so it won't slow down your application.
官方主頁:

http://jolbox.com/
下載地址:http://jolbox.com/bonecp/downloads/maven/com/jolbox/bonecp/
目前最新版本為:0.6.7.2
依賴的jar包:

1.A database that accepts connections

2.A driver to go with it

3.Google Guava library, available for free from here.

4.The SLF4J logginglibrary.

5.JDK1.5 or higher.


bonecp-0.7.0.jar

google-collections-1.0.jar


log4j-1.2.15.jar
mysql-connector-java-5.1.6-bin.jar(mysql驅動)
slf4j-api-1.5.10.jar
slf4j-log4j12-1.5.10.jar
以上jar包可以在這裡下載http://jolbox.com/bonecp/downloads/maven/

在jdbc中使用BoneCP連線池。

package com.bonecp;
 
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;
 
publicclass ExampleJDBC {
 
    
publicstaticvoid main(String[] args) {
        BoneCP connectionPool 
=null;
        Connection connection 
=null;
 
        
try {
            
// load the database driver (make sure this is in your classpath!)            Class.forName("com.mysql.jdbc.Driver");
        } 
catch (Exception e) {
            e.printStackTrace();
            
return;
        }
        
        
try {
            
// setup the connection pool            BoneCPConfig config =new BoneCPConfig();
            config.setJdbcUrl(
"jdbc:mysql://localhost:3306/demo"); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb            config.setUsername("root"); 
            config.setPassword(
"root");
            
//設定每60秒檢查資料庫中的空閒連線數<!-- 檢查資料庫連線池中空閒連線的間隔時間,單位是分,預設值:240,如果要取消則設定為0 -->
            config.setIdleConnectionTestPeriod(60);
            
//設定連線空閒時間 <!-- 連線池中未使用的連結最大存活時間,單位是分,預設值:60,如果要永遠存活設定為0 -->
            config.setIdleMaxAge(240);
            
//設定每個分割槽中的最大連線數 30            config.setMaxConnectionsPerPartition(30);
            
//設定每個分割槽中的最小連線數 10            config.setMinConnectionsPerPartition(10);
            
//當連線池中的連線耗盡的時候 BoneCP一次同時獲取的連線數 <!-- 每次去拿資料庫連線的時候一次性要拿幾個,預設值:2 -->
            config.setAcquireIncrement(5);
            
//連線釋放處理   每個分割槽釋放連結助理程序的數量,預設值:3,除非你的一個數據庫連線的時間內做了很多工作,不然過多的助理程序會影響你的效能
            config.setReleaseHelperThreads(3);
            
//設定分割槽  分割槽數為3 <!-- 分割槽數 ,預設值2,最小1,推薦3-4,視應用而定-->
            config.setPartitionCount(3);
            
//設定配置引數            connectionPool =new BoneCP(config); // setup the connection pool            
            connection 
= connectionPool.getConnection(); // fetch a connectionif (connection !=null){
                System.out.println(
"Connection successful!");
                Statement stmt 
= connection.createStatement();
                ResultSet rs 
= stmt.executeQuery(" select * from person "); // do something with the connection.while(rs.next()){
                    System.out.println(rs.getString(
1)); // should print out "1"'                    System.out.println(rs.getString(2)); // 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();
                }
            }
        }
    }
}

使用DataSource

package com.bonecp;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.jolbox.bonecp.BoneCPDataSource;

publicclass ExampleDataSource {
    
    
publicstaticvoid main(String[] args) {
        
        Connection connection 
=null;
        
        
try {
            Class.forName(
"com.mysql.jdbc.Driver");
        } 
catch (Exception e) {
            e.printStackTrace();
        }
        
        BoneCPDataSource dataSource
=new BoneCPDataSource();
        dataSource.setUsername(
"root");
        dataSource.setPassword(
"root");
        dataSource.setJdbcUrl(
"jdbc:mysql://localhost:3306/demo");
        dataSource.setMaxConnectionsPerPartition(
10);
        dataSource.setMinConnectionsPerPartition(
5);
        dataSource.setIdleConnectionTestPeriod(
60);
        dataSource.setIdleMaxAge(
240);
        dataSource.setAcquireIncrement(
5);
        dataSource.setReleaseHelperThreads(
3);
        
try {
            connection
=dataSource.getConnection();
            
if (connection !=null){
                System.out.println(
"Connection successful!");
                Statement stmt 
= connection.createStatement();
                ResultSet rs 
= stmt.executeQuery(" select * from person "); // do something with the connection.while(rs.next()){
                    System.out.println(rs.getString(
1)); // should print out "1"'                    System.out.println(rs.getString(2)); // should print out "1"'                }
            }
        } 
catch (SQLException e) {
            e.printStackTrace();
        }
finally{
            
try {
                connection.close();
            } 
catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        
    }
    
}


在Hibernate中使用BoneCP
在Hibernate中使用BoneCP除了需要上面提到的jar包之外,還需要下載一個名為bonecp-provider-0.7.0.jar的bonecp-provider的jar包,它的下載位置是:http://jolbox.com/bonecp/downloads/maven/com/jolbox/bonecp-provider/0.7.0/bonecp-provider-0.7.0.jar。
除此之外,還需要做如下配置:

  1. <!-- Hibernate SessionFactory -->
  2. <beanid="sessionFactory"class="org.springframework.orm.hibernate.LocalSessionFactoryBean"autowire="autodetect">
  3. <propertyname="hibernateProperties">
  4. <props>
  5. <propkey="hibernate.connection.provider_class">com.jolbox.bonecp.provider.BoneCPConnectionProvider</prop>
  6. <propkey="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
  7. <propkey="hibernate.connection.url">jdbc:mysql://127.0.0.1/yourdb</prop>
  8. <propkey="hibernate.connection.username">root</prop>
  9. <propkey="hibernate.connection.password">abcdefgh</prop>
  10. <propkey="bonecp.idleMaxAge">240</prop>
  11. <propkey="bonecp.idleConnectionTestPeriod">60</prop>
  12. <propkey="bonecp.partitionCount">3</prop>
  13. <propkey="bonecp.acquireIncrement">10</prop>
  14. <propkey="bonecp.maxConnectionsPerPartition">60</prop>
  15. <propkey="bonecp.minConnectionsPerPartition">20</prop>
  16. <propkey="bonecp.statementsCacheSize">50</prop>
  17. <propkey="bonecp.releaseHelperThreads">3</prop>
  18. </props>
  19. </property>
  20. </bean

xml方式配置bonecp

<?xml version="1.0" encoding="UTF-8"?><bonecp-config><default-config><property name="jdbcUrl">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property><property name="username">scott</property><property name="password">tiger</property><property name="partitionCount">3</property><property name="maxConnectionsPerPartition">30</property><property name="minConnectionsPerPartition">10</property><property name="acquireIncrement">3</property></default-config></bonecp-config>

連線程式碼

package com.bonecp;
 
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;
 
publicclass ExampleJDBC {
 
    
publicstaticvoid main(String[] args) {
        BoneCP connectionPool 
=null;
        
        Connection connection 
=null;
        
try {
            
// load the database driver (make sure this is in your classpath!)            Class.forName("oracle.jdbc.driver.OracleDriver");
        } 
catch (Exception e) {
            e.printStackTrace();
            
return;
        }
        
        
try {
            
// setup the connection pool            BoneCPConfig config =null;
            
try {
                config 
=new BoneCPConfig("bonecp-config.xml");
            } 
catch (Exception e) {
                e.printStackTrace();
            }
            
//設定配置引數            connectionPool =new BoneCP(config); // setup the connection poollong startTime=System.currentTimeMillis();
            
//建立100個連線for (int i =0; i <100; i++) {
                connection 
= connectionPool.getConnection(); // fetch a connection            }
            
long endtTime=System.currentTimeMillis();
            
            System.out.println(
"-------->total seconds :"+(endtTime-startTime));
            
            
if (connection !=null){
                System.out.println(
"Connection successful!");
                Statement stmt 
= connection.createStatement();
                ResultSet rs 
= stmt.executeQuery(" select * from emp "); // do something with the connection.while(rs.next()){
                    System.out.println(rs.getString(
1)); // should print out "1"'                    System.out.println(rs.getString(2)); // 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();
                }
            }
        }
    }
}