Java資料庫連接池實現原理

來源:互聯網
上載者:User

標籤:

一般來說,Java應用程式訪問資料庫的過程是:
  ①裝載資料庫驅動程式;
  ②通過jdbc建立資料庫連接;
  ③訪問資料庫,執行sql語句;

  ④斷開資料庫連接。

public class DBConnection {private Connection con;//定義資料庫連接類對象private PreparedStatement pstm;private String user="root";//串連資料庫使用者名稱private String password="123456";//串連資料庫密碼private String driverName="com.mysql.jdbc.Driver";//資料庫驅動private String url="jdbc:mysql://localhost:3306/qingqingtuan";//串連資料庫的URL,後面的是為了防止插入資料 庫出現亂碼,?useUnicode=true&characterEncoding=UTF-8//建構函式public DBConnection(){}/**建立資料庫連接*/public Connection getConnection(){try{Class.forName("com.mysql.jdbc.Driver");}catch(ClassNotFoundException e){System.out.println("載入資料庫驅動失敗!");e.printStackTrace();}try {con=DriverManager.getConnection(url,user,password);//擷取資料庫連接} catch (SQLException e) {System.out.println("建立資料庫連接失敗!");con=null;e.printStackTrace();}return con;//返回資料庫連接對象} List<Shop> mShopList=new ArrayList<Shop>(); mConnection=new DBConnection().getConnection(); if(mConnection!=null){try {String sql="select * from shop";PreparedStatement pstm=mConnection.prepareStatement(sql);ResultSet rs=pstm.executeQuery();while(rs.next()){                                ......//封裝PoPj的操作                                }                                rs.close();pstm.close();   } catch (SQLException e) {e.printStackTrace();}finally{try {if(mConnection!=null){mConnection.close();}} catch (SQLException e) {e.printStackTrace();}} 

                     


程式開發過程中,存在很多問題:

首先,每一次web請求都要建立一次資料庫連接。建立串連是一個費時的活動,每次都得花費0.05s~1s的時間,而且系統還要分配記憶體資源。這個時間對於一次或幾次資料庫操作,或許感覺不出系統有多大的開銷。

可是對於現在的web應用,尤其是大型電子商務網站,同時有幾百人甚至幾千人線上是很正常的事。在這種情況下,頻繁的進行資料庫連接操作勢必佔用很多的系統資源,網站的響應速度必定下降,嚴重的甚至會造成伺服器的崩潰。不是危言聳聽,這就是制約某些電子商務網站發展的技術瓶頸問題。其次,對於每一次資料庫連接,使用完後都得斷開。否則,如果程式出現異常而未能關閉,將會導致資料庫系統中的記憶體流失,最終將不得不重啟資料庫

     通過上面的分析,我們可以看出來,“資料庫連接”是一種稀缺的資源,為了保障網站的正常使用,應該對其進行妥善管理。其實我們查詢完資料庫後,如果不關閉串連,而是暫時存放起來,當別人使用時,把這個串連給他們使用。就避免了一次建立資料庫連接和斷開的操作時間消耗。

資料庫連接池的基本思想:就是為資料庫連接建立一個“緩衝池”。預先在緩衝池中放入一定數量的串連,當需要建立資料庫連接時,只需從“緩衝池”中取出一個,使用完畢之後再放回去。我們可以通過設定串連池最大串連數來防止系統無盡的與資料庫連接

建立資料庫連接池大概有3個步驟:

① 建立ConnectionPool執行個體,並初始化建立10個串連,儲存在Vector中(安全執行緒)
② 實現getConnection()從串連庫中擷取一個可用的串連
③ returnConnection(conn) 提供將串連放回串連池中方法


ConnectionPool.java

//////////////////////////////// 資料庫連接池類 ConnectionPool.java /////////////////////////////////////////* 這個例子是根據POSTGRESQL資料庫寫的, 請用的時候根據實際的資料庫調整。 調用方法如下: ① ConnectionPool connPool  = new ConnectionPool("com.microsoft.jdbc.sqlserver.SQLServerDriver" ,"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=MyDataForTest" ,"Username" ,"Password"); ② connPool .createPool(); Connection conn = connPool .getConnection(); connPool.returnConnection(conn);  connPool.refreshConnections(); connPool.closeConnectionPool(); */import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.Driver;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import java.util.Enumeration;import java.util.Vector;public class ConnectionPool {private String jdbcDriver = ""; // 資料庫驅動private String dbUrl = ""; // 資料 URLprivate String dbUsername = ""; // 資料庫使用者名稱private String dbPassword = ""; // 資料庫使用者密碼private String testTable = ""; // 測試連接是否可用的測試表名,預設沒有測試表private int initialConnections = 10; // 串連池的初始大小private int incrementalConnections = 5;// 串連池自動增加的大小private int maxConnections = 50; // 串連池最大的大小private Vector connections = null; // 存放串連池中資料庫連接的向量 , 初始時為 null// 它中存放的對象為 PooledConnection 型/** * 建構函式 *  * @param jdbcDriver *            String JDBC 驅動類串 * @param dbUrl *            String 資料庫 URL * @param dbUsername *            String 串連資料庫使用者名稱 * @param dbPassword *            String 串連資料庫使用者的密碼 *  */public ConnectionPool(String jdbcDriver, String dbUrl, String dbUsername,String dbPassword) {this.jdbcDriver = jdbcDriver;this.dbUrl = dbUrl;this.dbUsername = dbUsername;this.dbPassword = dbPassword;}/** * 返回串連池的初始大小 *  * @return 初始串連池中可獲得的串連數量 */public int getInitialConnections() {return this.initialConnections;}/** * 設定串連池的初始大小 *  * @param 用於設定初始串連池中串連的數量 */public void setInitialConnections(int initialConnections) {this.initialConnections = initialConnections;}/** * 返回串連池自動增加的大小 、 *  * @return 串連池自動增加的大小 */public int getIncrementalConnections() {return this.incrementalConnections;}/** * 設定串連池自動增加的大小 *  * @param 串連池自動增加的大小 */public void setIncrementalConnections(int incrementalConnections) {this.incrementalConnections = incrementalConnections;}/** * 返回串連池中最大的可用串連數量 *  * @return 串連池中最大的可用串連數量 */public int getMaxConnections() {return this.maxConnections;}/** * 設定串連池中最大可用的串連數量 *  * @param 設定串連池中最大可用的串連數量值 */public void setMaxConnections(int maxConnections) {this.maxConnections = maxConnections;}/** * 擷取測試資料庫表的名字 *  * @return 測試資料庫表的名字 */public String getTestTable() {return this.testTable;}/** * 設定測試表的名字 *  * @param testTable *            String 測試表的名字 */public void setTestTable(String testTable) {this.testTable = testTable;}/** *  * 建立一個資料庫連接池,串連池中的可用串連的數量採用類成員 initialConnections 中設定的值 */public synchronized void createPool() throws Exception {// 確保串連池沒有建立// 如果串連池己經建立了,儲存串連的向量 connections 不會為空白if (connections != null) {return; // 如果己經建立,則返回}// 執行個體化 JDBC Driver 中指定的驅動類執行個體Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance());DriverManager.registerDriver(driver); // 註冊 JDBC 驅動程式// 建立儲存串連的向量 , 初始時有 0 個元素connections = new Vector();// 根據 initialConnections 中設定的值,建立串連。createConnections(this.initialConnections);// System.out.println(" 資料庫連接池建立成功! ");}/** * 建立由 numConnections 指定數目的資料庫連接 , 並把這些串連 放入 connections 向量中 *  * @param numConnections *            要建立的資料庫連接的數目 */private void createConnections(int numConnections) throws SQLException {// 迴圈建立指定數目的資料庫連接for (int x = 0; x < numConnections; x++) {// 是否串連池中的資料庫連接的數量己經達到最大?最大值由類成員 maxConnections// 指出,如果 maxConnections 為 0 或負數,表示串連數量沒有限制。// 如果串連數己經達到最大,即退出。if (this.maxConnections > 0&& this.connections.size() >= this.maxConnections) {break;}// add a new PooledConnection object to connections vector// 增加一個串連到串連池中(向量 connections 中)try {connections.addElement(new PooledConnection(newConnection()));} catch (SQLException e) {System.out.println(" 建立資料庫連接失敗! " + e.getMessage());throw new SQLException();}// System.out.println(" 資料庫連接己建立 ......");}}/** * 建立一個新的資料庫連接並返回它 *  * @return 返回一個新建立的資料庫連接 */private Connection newConnection() throws SQLException {// 建立一個資料庫連接Connection conn = DriverManager.getConnection(dbUrl, dbUsername,dbPassword);// 如果這是第一次建立資料庫連接,即檢查資料庫,獲得此資料庫允許支援的// 最大客戶串連數目// connections.size()==0 表示目前沒有串連己被建立if (connections.size() == 0) {DatabaseMetaData metaData = conn.getMetaData();int driverMaxConnections = metaData.getMaxConnections();// 資料庫返回的 driverMaxConnections 若為 0 ,表示此資料庫沒有最大// 串連限制,或資料庫的最大串連限制不知道// driverMaxConnections 為返回的一個整數,表示此資料庫允許客戶串連的數目// 如果串連池中設定的最大串連數量大於資料庫允許的串連數目 , 則置串連池的最大// 串連數目為資料庫允許的最大數目if (driverMaxConnections > 0&& this.maxConnections > driverMaxConnections) {this.maxConnections = driverMaxConnections;}}return conn; // 返回建立的新的資料庫連接}/** * 通過調用 getFreeConnection() 函數返回一個可用的資料庫連接 , 如果當前沒有可用的資料庫連接,並且更多的資料庫連接不能創 * 建(如串連池大小的限制),此函數等待一會再嘗試擷取。 *  * @return 返回一個可用的資料庫連接對象 */public synchronized Connection getConnection() throws SQLException {// 確保串連池己被建立if (connections == null) {return null; // 串連池還沒建立,則返回 null}Connection conn = getFreeConnection(); // 獲得一個可用的資料庫連接// 如果目前沒有可以使用的串連,即所有的串連都在使用中while (conn == null) {// 等一會再試// System.out.println("Wait");wait(250);conn = getFreeConnection(); // 重新再試,直到獲得可用的串連,如果// getFreeConnection() 返回的為 null// 則表明建立一批串連後也不可獲得可用串連}return conn;// 返回獲得的可用的串連}/** * 本函數從串連池向量 connections 中返回一個可用的的資料庫連接,如果 當前沒有可用的資料庫連接,本函數則根據 * incrementalConnections 設定 的值建立幾個資料庫連接,並放入串連池中。 如果建立後,所有的串連仍都在使用中,則返回 null *  * @return 返回一個可用的資料庫連接 */private Connection getFreeConnection() throws SQLException {// 從串連池中獲得一個可用的資料庫連接Connection conn = findFreeConnection();if (conn == null) {// 如果目前串連池中沒有可用的串連// 建立一些串連createConnections(incrementalConnections);// 重新從池中尋找是否有可用串連conn = findFreeConnection();if (conn == null) {// 如果建立串連後仍獲得不到可用的串連,則返回 nullreturn null;}}return conn;}/** * 尋找串連池中所有的串連,尋找一個可用的資料庫連接, 如果沒有可用的串連,返回 null *  * @return 返回一個可用的資料庫連接 */private Connection findFreeConnection() throws SQLException {Connection conn = null;PooledConnection pConn = null;// 獲得串連池向量中所有的對象Enumeration enumerate = connections.elements();// 遍曆所有的對象,看是否有可用的串連while (enumerate.hasMoreElements()) {pConn = (PooledConnection) enumerate.nextElement();if (!pConn.isBusy()) {// 如果此對象不忙,則獲得它的資料庫連接並把它設為忙conn = pConn.getConnection();pConn.setBusy(true);// 測試此串連是否可用if (!testConnection(conn)) {// 如果此串連不可再用了,則建立一個新的串連,// 並替換此停用連線物件,如果建立失敗,返回 nulltry {conn = newConnection();} catch (SQLException e) {System.out.println(" 建立資料庫連接失敗! " + e.getMessage());return null;}pConn.setConnection(conn);}break; // 己經找到一個可用的串連,退出}}return conn;// 返回找到到的可用串連}/** * 測試一個串連是否可用,如果不可用,關掉它並返回 false 否則可用返回 true *  * @param conn *            需要測試的資料庫連接 * @return 返回 true 表示此串連可用, false 表示不可用 */private boolean testConnection(Connection conn) {try {// 判斷測試表是否存在if (testTable.equals("")) {// 如果測試表為空白,試著使用此串連的 setAutoCommit() 方法// 來判斷串連否可用(此方法只在部分資料庫可用,如果不可用 ,// 拋出異常)。注意:使用測試表的方法更可靠conn.setAutoCommit(true);} else {// 有測試表的時候使用測試表測試// check if this connection is validStatement stmt = conn.createStatement();stmt.execute("select count(*) from " + testTable);}} catch (SQLException e) {// 上面拋出異常,此串連己不可用,關閉它,並返回 false;closeConnection(conn);return false;}// 串連可用,返回 truereturn true;}/** * 此函數返回一個資料庫連接到串連池中,並把此串連置為空白閑。 所有使用串連池獲得的資料庫連接均應在不使用此串連時返回它。 *  * @param 需返回到串連池中的連線物件 */public void returnConnection(Connection conn) {// 確保串連池存在,如果串連沒有建立(不存在),直接返回if (connections == null) {System.out.println(" 串連池不存在,無法返回此串連到串連池中 !");return;}PooledConnection pConn = null;Enumeration enumerate = connections.elements();// 遍曆串連池中的所有串連,找到這個要返回的連線物件while (enumerate.hasMoreElements()) {pConn = (PooledConnection) enumerate.nextElement();// 先找到串連池中的要返回的連線物件if (conn == pConn.getConnection()) {// 找到了 , 設定此串連為空白閑狀態pConn.setBusy(false);break;}}}/** * 重新整理串連池中所有的連線物件 *  */public synchronized void refreshConnections() throws SQLException {// 確保串連池己創新存在if (connections == null) {System.out.println(" 串連池不存在,無法重新整理 !");return;}PooledConnection pConn = null;Enumeration enumerate = connections.elements();while (enumerate.hasMoreElements()) {// 獲得一個連線物件pConn = (PooledConnection) enumerate.nextElement();// 如果對象忙則等 5 秒 ,5 秒後直接重新整理if (pConn.isBusy()) {wait(5000); // 等 5 秒}// 關閉此串連,用一個新的串連代替它。closeConnection(pConn.getConnection());pConn.setConnection(newConnection());pConn.setBusy(false);}}/** * 關閉串連池中所有的串連,並清空串連池。 */public synchronized void closeConnectionPool() throws SQLException {// 確保串連池存在,如果不存在,返回if (connections == null) {System.out.println(" 串連池不存在,無法關閉 !");return;}PooledConnection pConn = null;Enumeration enumerate = connections.elements();while (enumerate.hasMoreElements()) {pConn = (PooledConnection) enumerate.nextElement();// 如果忙,等 5 秒if (pConn.isBusy()) {wait(5000); // 等 5 秒}// 5 秒後直接關閉它closeConnection(pConn.getConnection());// 從串連池向量中刪除它connections.removeElement(pConn);}// 置串連池為空白connections = null;}/** * 關閉一個資料庫連接 *  * @param 需要關閉的資料庫連接 */private void closeConnection(Connection conn) {try {conn.close();} catch (SQLException e) {System.out.println(" 關閉資料庫連接出錯: " + e.getMessage());}}/** * 使程式等待給定的毫秒數 *  * @param 給定的毫秒數 */private void wait(int mSeconds) {try {Thread.sleep(mSeconds);} catch (InterruptedException e) {}}/** *  * 內部使用的用於儲存串連池中連線物件的類 此類中有兩個成員,一個是資料庫的串連,另一個是指示此串連是否 正在使用的標誌。 */class PooledConnection {Connection connection = null;// 資料庫連接boolean busy = false; // 此串連是否正在使用的標誌,預設沒有正在使用// 建構函式,根據一個 Connection 構告一個 PooledConnection 對象public PooledConnection(Connection connection) {this.connection = connection;}// 返回此對象中的串連public Connection getConnection() {return connection;}// 設定此對象的,串連public void setConnection(Connection connection) {this.connection = connection;}// 獲得對象串連是否忙public boolean isBusy() {return busy;}// 設定對象的串連正在忙public void setBusy(boolean busy) {this.busy = busy;}}}
ConnectionPoolUtils.java

/*串連池工具類,返回唯一的一個資料庫連接池對象,單例模式*/public class ConnectionPoolUtils {private ConnectionPoolUtils(){};//私人靜態方法private static ConnectionPool poolInstance = null;public static ConnectionPool GetPoolInstance(){if(poolInstance == null) {poolInstance = new ConnectionPool( "com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8", "root", "123456");try {poolInstance.createPool();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}return poolInstance;}}

ConnectionPoolTest.java

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class ConnectionTest {/** * @param args * @throws Exception  */public static void main(String[] args) throws Exception { try {      /*使用串連池建立100個串連的時間*/        /*// 建立資料庫連接庫對象       ConnectionPool connPool = new ConnectionPool("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/test", "root", "123456");       // 建立資料庫連接庫           connPool.createPool();*/       ConnectionPool  connPool=ConnectionPoolUtils.GetPoolInstance();//單例模式建立串連池對象            // SQL測試語句       String sql = "Select * from pet";       // 設定程式運行起始時間       long start = System.currentTimeMillis();             // 迴圈測試100次資料庫連接              for (int i = 0; i < 100; i++) {                  Connection conn = connPool.getConnection(); // 從串連庫中擷取一個可用的串連                  Statement stmt = conn.createStatement();                  ResultSet rs = stmt.executeQuery(sql);                  while (rs.next()) {                      String name = rs.getString("name");                   //  System.out.println("查詢結果" + name);                  }                  rs.close();                  stmt.close();                  connPool.returnConnection(conn);// 串連使用完後釋放串連到串連池              }              System.out.println("經過100次的迴圈調用,使用串連池花費的時間:"+ (System.currentTimeMillis() - start) + "ms");              // connPool.refreshConnections();//重新整理資料庫連接池中所有串連,即不管串連是否正在運行,都把所有串連都釋放並放回到串連池。注意:這個耗時比較大。             connPool.closeConnectionPool();// 關閉資料庫連接池。注意:這個耗時比較大。              // 設定程式運行起始時間              start = System.currentTimeMillis();                            /*不使用串連池建立100個串連的時間*/             // 匯入驅動              Class.forName("com.mysql.jdbc.Driver");              for (int i = 0; i < 100; i++) {                  // 建立串連                 Connection conn = DriverManager.getConnection(                          "jdbc:mysql://localhost:3306/test", "root", "123456");                  Statement stmt = conn.createStatement();                  ResultSet rs = stmt.executeQuery(sql);                 while (rs.next()) {                  }                 rs.close();                 stmt.close();                 conn.close();// 關閉串連             }             System.out.println("經過100次的迴圈調用,不使用串連池花費的時間:"                     + (System.currentTimeMillis() - start) + "ms");         } catch (SQLException e) {            e.printStackTrace();         } catch (ClassNotFoundException e) {             e.printStackTrace();        }}

Java資料庫連接池實現原理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.