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.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章