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>

四大流行的java连接池之BoneCP篇的更多相关文章

  1. 四大流行的jdbc连接池之C3P0篇

    C3P0是一个开放源代码的JDBC连接池,它在lib目录中与Hibernate一起发布,包括了实现jdbc3和jdbc2扩展规范说明的Connection 和Statement 池的DataSourc ...

  2. 四个流行的Java连接池之Proxool篇

    Proxool是一个JavaSQL Driver驱动程序,提供了对你选择的其它类型的驱动程序的连接池封装.可以非常简单的移植到现存的代码中.完全可配置.快速,成熟,健壮.可以透明地为你现存的JDBC驱 ...

  3. 几个主流java连接池

    池(Pool)技术在一定程度上可以明显优化服务器应用程序的性能,提高程序执行效率和降低系统资源开销.这里所说的池是一种广义上的池,比如数据库连接池.线程池.内存池.对象池等.其中,对象池可以看成保存对 ...

  4. 转载: 几个主流的Java连接池整理

    https://www.cnblogs.com/linjian/p/4831088.html 池(Pool)技术在一定程度上可以明显优化服务器应用程序的性能,提高程序执行效率和降低系统资源开销.这里所 ...

  5. 几个主流的Java连接池整理

    池(Pool)技术在一定程度上可以明显优化服务器应用程序的性能,提高程序执行效率和降低系统资源开销.这里所说的池是一种广义上的池,比如数据库连接池.线程池.内存池.对象池等.其中,对象池可以看成保存对 ...

  6. [JavaEE] 了解Java连接池

    转载自51CTO http://developer.51cto.com/art/201006/207768.htm 51CTO曾经为我们简单的介绍过Java连接池.要了解Java连接池我们先要了解数据 ...

  7. Java 连接池的工作原理(转)

    原文:Java 连接池的工作原理 什么是连接? 连接,是我们的编程语言与数据库交互的一种方式.我们经常会听到这么一句话“数据库连接很昂贵“. 有人接受这种说法,却不知道它的真正含义.因此,下面我将解释 ...

  8. Redis Java连接池调研

    Redis Java连接池调研 线上服务,由于压力大报错RedisTimeOut,但是需要定位到底问题出现在哪里? 查看Redis慢日志,slowlog get 发现耗时最大的也是11000us也就是 ...

  9. 【JAVA】 Java 连接池的工作原理

    什么是连接?         连接,是我们的编程语言与数据库交互的一种方式.我们经常会听到这么一句话“数据库连接很昂贵“.         有人接受这种说法,却不知道它的真正含义.因此,下面我将解释它 ...

随机推荐

  1. foreach学习笔记

    对集合进行遍历 只能获取集合元素,但是不能对集合进行操作. 迭代器除了遍历,还可以进行remove的动作. 如果是用ListIterator,还可以在遍历过程中进行增删改查的动作. for(Strin ...

  2. 《Java TCP/IP Socket 编程 》读书笔记之十一:深入剖析socket——TCP套接字的生命周期

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/16113083 建立TCP连接      新的Socket实例创建后,就立即能用于发送和接收 ...

  3. jQuery $.fn.extend方式自定义插件

    之前例子是扩展jQuery的工具方法,即通过$.xxx(para);的形式来使用的.下面是扩展jquery对象的方法,即任意一个jquery对象都已访问. 具体如下: wyl.js: (functio ...

  4. Windows下搭建objective C开发环境

    摘自:http://blog.csdn.net/zhanghefu/article/details/18320827 最近打算针对iPhone.iPod touch和iPad开发一些应用,所以,需要开 ...

  5. C# Programming Study #2

    readonly (C# Reference) readonly  关键字是可以在字段上使用的修饰符.  当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者 ...

  6. ipa制作

    打包ipa步骤: 项目名称 -> edit scheme -> 如图选择release 点击close后,选择真机 然后command+b编译程序,右击app,show in Finder ...

  7. 高级UNIX环境编程7 进程

    每个程序都会收到一张环境表 extern char **environ; c程序的存储空间布局: 正文段:共享,只读 初始化数据段:存函数以外的赋值 非初始化数据段(bbs):block starte ...

  8. Debian下Apache配置多域名访问

    请见Github博客:http://wuxichen.github.io/Myblog/php/2014/10/10/DebianApacheSetting.html

  9. Objective-C基础教程读书笔记(6)

    第6章 源文件组织 到目前为止,我们讨论过的所有项目都是把源代码统统放入main.m文件中.类的main()函数,@interface和@implementation部分都被塞入同一个文件里.这种结构 ...

  10. Open vswitch 之Qos rate-limiting 原理

    Openvswitch之Qos rate-limiting原理 OVS的qosrate-limiting功能是采用令牌桶(Token-Bucket)机制进行的.这里的“令牌桶”是指网络设备的内部存储池 ...