Oracle數(shù)據(jù)庫的密集型實際應(yīng)用程序的開發(fā)
我們都知道再開發(fā)Oracle數(shù)據(jù)庫的密集型實際應(yīng)用程序時,使用相關(guān)連接池而受益。之所以是因為這樣,我們才能夠重用連接,而不是在每次請求連接時都重新創(chuàng)建一個新連接。連接池節(jié)約了創(chuàng)建新數(shù)據(jù)庫連接所需的資源,并提高了應(yīng)用程序的性能,因為創(chuàng)建新連接始終是一個性能密集型操作。
Oracle Universal Connection Pool for JDBC 表示一個用于緩存 JDBC 連接的全功能實現(xiàn)。UCP 是一個非常有用的特性,它將使您可以重用連接對象,從而可以提高獲取連接過程的速度并節(jié)約打開新數(shù)據(jù)庫連接所需的資源。
假設(shè)您希望創(chuàng)建一個 UCP JDBC 連接池來重用到 HR/HR Oracle 數(shù)據(jù)庫示例模式的已建立連接。以下程序是一個 UCP JDBC 連接池實際運行的簡單示例,將向您展示如何完成此操作。您將首先創(chuàng)建一個支持池的數(shù)據(jù)源實例,然后設(shè)置連接和池的屬性。完成后,您將從池中借用一個連接,然后使用該連接與數(shù)據(jù)庫交互。***,您將關(guān)閉該連接,將其返回到池。
- import java.sql.*; import oracle.ucp.jdbc.PoolDataSourceFactory;
import oracle.ucp.jdbc.PoolDataSource; public class UcpConnection
{ public static void main(String args[]) throws SQLException
{ try { //Creating a pool-enabled data source PoolDataSource pds
= PoolDataSourceFactory.getPoolDataSource();
//Setting connection properties of the data source pds.
setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
pds.setURL("jdbc:oracle:thin:@//localhost:1521/XE"); pds.setUser("hr");
pds.setPassword("hr"); //Setting pool properties pds.setInitialPoolSize(5);
pds.setMinPoolSize(5); pds.setMaxPoolSize(10);
//Borrowing a connection fro th oo Connection con = pds.getConnection();- ount(); System.out.println("\nAvailable connections:
" + avlConnCount); int brwConnCount = pds.getBorrowedConnectionsCount();
System.out.println("\nBorrowed connections: " + brwConnCount);
//Working with the connection Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select user from dual");
while(rs.next()) System.out.println("\nConnected as: "+rs.getString(1));
rs.close(); //Returning the connection to the pool conn.close(); conn=null;
System.out.println("\nConnection returned to the pool");
//Checking the number of available and borrowed connections again avlConnCount =
pds.getAvailableConnectionsCount();
System.out.println("\nAvailable connections: " + avlConnCount);
brwConnCount = pds.getBorrowedConnectionsCount();
System.out.println("\nBorrowed connections: " + brwConnCount); }
catch(SQLException e)
{ System.out.println("\nAn SQL exception occurred : " + e.getMessage()); } } }
這里值得注意的是關(guān)閉連接時的變化。以上程序的輸出闡釋了關(guān)閉從 UCP JDBC 連接池中借用的連接將使該連接返回到池,以供下一次連接請求使用。
該應(yīng)用程序的輸出應(yīng)如下所示:
- Connection borrowed from the poolAvailable connections:
4Borrowed connections: 1Connected as: HRConnection returned
to the poolAvailable connections: 5Borrowed connections: 0
上述的相關(guān)內(nèi)容就是使用 UCP 緩存 JDBC 連接對開發(fā)Oracle數(shù)據(jù)庫密集型應(yīng)用程序的描述,希望會給你帶來一些幫助在此方面。
【編輯推薦】