2010年8月25号---数据库连接池之---bonecp简单连接池的创建和使用

在做数据库链接的时候,发现原来的jdbc根本不能满足程序中大量用户的连接请求,于是开始使用数据库连接池。原因在于建立数据库链接是一个非常耗时的行为,所以使用数据库连接池预先同数据库建立一些链接,放在内存中,应用程序需要建立数据库连接时,直接到连接池中申请一个就行,用完之后再放回去。

 

     Many Apache projects support interaction with a relational database. Creating a new connection for each user be time consuming(often requiring multiple seconds of clock time), in order to perform a database transaction that might take millseconds. Opening a connection per user can be unfeasible in a publicly-hosted Internet application where the number of simultaneous users can be very large.Accordingly, developers often wish to share a "pool" of open connections between all of the application's current users. The number of users actually performing a request at any given time is usually a very small percentage of the total number of active users, and during request processing is the only time that a database connection is required . The application itself logs into the DBMS, and handles any user account issues internally.

    There are several Database Connection Pools already available, both within Apache products and elsewhere. This Commons package provides an opportunity to coordinate the efforts required to create and maintain an efficient, feature-rich package under the ASF license.

 

这些是apache DBCP 的介绍性内容,解释了为什么需要连接池的内容;

我在这里使用了BoneCP作为数据库连接池提供端平台。实现方式在其帮助文档上也有,按照这个过程来建立连接池就可以了,当然关于boneCP 的使用还有很多内容和复杂的东西。可以根据boneCP API深入的学习:

这里引用一下:

 

This document describes the API of BoneCP. Usage is simple:

  • Load the JDBC driver or provide a datasource.
  • Configure BoneCP (via a datasource or manually)
  • Call pool.getConnection() or pool.getAsyncConnection()

The example below sets up the connection pool (manually) and obtains a connection. For clarity it omits exception handling.

     
// load the database driver (make sure this is in your classpath!)
Class.forName("org.hsqldb.jdbcDriver");
// setup the connection pool
BoneCPConfig config = new BoneCPConfig();
// jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
config.setJdbcUrl("jdbc:hsqldb:mem:test"); 
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("Connection successful!");
    Statement stmt = connection.createStatement();
    // do something with the connection.
        ResultSet rs = stmt.executeQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS"); 
        while(rs.next()){
                System.out.println(rs.getString(1)); // should print out "1"'
        }
}
                        
connection.close(); // close the connection
connectionPool.shutdown(); // shutdown connection pool.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章