經典的單例模式c3p0來控制資料庫連接池

來源:互聯網
上載者:User

 


 

 

1.建立ConnectionManager.java

package com.c3p0.datapools;//資料庫連接池  單例模式import java.sql.Connection;import java.sql.SQLException;import com.mchange.v2.c3p0.ComboPooledDataSource;import com.mchange.v2.c3p0.DataSources;public final class ConnectionManager {    private static ConnectionManager instance;    private ComboPooledDataSource ds;    private ConnectionManager() throws Exception {                ds = new ComboPooledDataSource();        ds.setDriverClass("oracle.jdbc.driver.OracleDriver");        ds.setJdbcUrl("jdbc:oracle:thin:@127.0.0.1:1521:orcl");        ds.setUser("scott");        ds.setPassword("tiger");        //初始化時擷取三個串連,取值應在minPoolSize與maxPoolSize之間。Default: 3 initialPoolSize        ds.setInitialPoolSize(3);        //串連池中保留的最大串連數。Default:  15 maxPoolSize        ds.setMaxPoolSize(100);                //// 串連池中保留的最小串連數。        //ds.setMinPoolSize(1);                //當串連池中的串連耗盡的時候c3p0一次同時擷取的串連數。Default: 3 acquireIncrement          ds.setAcquireIncrement(1);        //每60秒檢查所有串連池中的空閑串連。Default: 0  idleConnectionTestPeriod        ds.setIdleConnectionTestPeriod(60);               //最大空閑時間,25000秒內未使用則串連被丟棄。若為0則永不丟棄。Default: 0  maxIdleTime        ds.setMaxIdleTime(25000);        //串連關閉時預設將所有未提交的操作復原。Default: false autoCommitOnClose        ds.setAutoCommitOnClose(true);        //定義所有串連測試都執行的測試語句。在使用串連測試的情況下這個一顯著提高測試速度。注意:        //測試的表必須在初始資料來源的時候就存在。Default: null  preferredTestQuery        ds.setPreferredTestQuery("select sysdate from dual");        // 因效能消耗大請只在需要的時候使用它。如果設為true那麼在每個connection提交的        // 時候都將校正其有效性。建議使用idleConnectionTestPeriod或automaticTestTable        // 等方法來提升串連測試的效能。Default: false testConnectionOnCheckout        ds.setTestConnectionOnCheckout(true);        //如果設為true那麼在取得串連的同時將校正串連的有效性。Default: false  testConnectionOnCheckin        ds.setTestConnectionOnCheckin(true);        //定義在從資料庫擷取新串連失敗後重複嘗試的次數。Default: 30  acquireRetryAttempts        ds.setAcquireRetryAttempts(30);        //兩次串連中間隔時間,單位毫秒。Default: 1000 acquireRetryDelay        ds.setAcquireRetryDelay(1000);        //擷取串連失敗將會引起所有等待串連池來擷取串連的線程拋出異常。但是資料來源仍有效        //保留,並在下次調用getConnection()的時候繼續嘗試擷取串連。如果設為true,那麼在嘗試        //擷取串連失敗後該資料來源將申明已斷開並永久關閉。Default: false  breakAfterAcquireFailure        ds.setBreakAfterAcquireFailure(true);                      //        <!--當串連池用完時用戶端調用getConnection()後等待擷取新串連的時間,逾時後將拋出        //        SQLException,如設為0則無限期等待。單位毫秒。Default: 0 -->        //        <property name="checkoutTimeout">100</property>        //        <!--c3p0將建一張名為Test的空表,並使用其內建的查詢語句進行測試。如果定義了這個參數那麼        //        屬性preferredTestQuery將被忽略。你不能在這張Test表上進行任何操作,它將只供c3p0測試        //        使用。Default: null-->        //        <property name="automaticTestTable">Test</property>        //        <!--JDBC的標準參數,用以控制資料來源內載入的PreparedStatements數量。但由於預緩衝的statements        //        屬於單個connection而不是整個串連池。所以設定這個參數需要考慮到多方面的因素。        //        如果maxStatements與maxStatementsPerConnection均為0,則緩衝被關閉。Default: 0-->        //        <property name="maxStatements">100</property>        //        <!--maxStatementsPerConnection定義了串連池內單個串連所擁有的最大緩衝statements數。Default: 0 -->        //        <property name="maxStatementsPerConnection"></property>        //        <!--c3p0是非同步作業的,緩慢的JDBC操作通過協助進程完成。擴充這些操作可以有效提升效能        //        通過多線程實現多個操作同時被執行。Default: 3-->        //        <property name="numHelperThreads">3</property>        //        <!--使用者修改系統配置參數執行前最多等待300秒。Default: 300 -->        //        <property name="propertyCycle">300</property>    }    public  static  final ConnectionManager getInstance() {        if (instance == null) {            try {                instance = new ConnectionManager();            } catch (Exception e) {                e.printStackTrace();            }        }        return instance;    }    public synchronized   final Connection getConnection() {        try {            return ds.getConnection();        } catch (SQLException e) {            e.printStackTrace();        }        return null;    }    protected void finalize() throws Throwable {        DataSources.destroy(ds); //關閉datasource        super.finalize();    }}

 

2.再建 TestC3p0.java

 

package com.c3p0.datapools;//調用資料庫連接池import java.sql.Connection;import java.sql.ResultSet;import java.sql.Statement;public class TestC3p0 {    public TestC3p0() {        // TODO 自動產生建構函式存根    }       public static void main(String[] args) {        // TODO 自動產生方法存根        ConnectionManager cm = ConnectionManager.getInstance();        Connection conn = null;        Statement stmt =  null;        ResultSet rs =    null;        String sql = "select *  from   xsjbxxb";             synchronized (sql) {         for (int i = 0; i < 10000; i++) {            try {                conn =  cm.getConnection();                System.out.println("conn="+conn+"and i="+i);                stmt = conn.createStatement();                rs =   stmt.executeQuery(sql);                while (rs.next()) {                 System.out.println(rs.getString(2));}               // rs.next();                        } catch (Exception ex) {                ex.printStackTrace();            } finally {                if (rs != null) {                    try {                        rs.close();                    } catch (Exception e) {                    }                }                            if (stmt != null) {                    try {                        stmt.close();                    } catch (Exception e) {                    }                }                if (conn != null) {                    try {                        conn.close();                    } catch (Exception e) {                    }                }            }            //try {            //    System.out.println(cm.ds.toString());            //    Thread.sleep(10000);            //} catch (Exception e) {            //    // TODO: handle exception            //}        }    }    }}

 

3.總結:經過測試,採用單例模式,資料庫中存在的串連明顯減少,那麼就可以支援oracle預設情況下150的並發數。

如果硬體資源允許的話,可以修改oracle參數來提高並發數。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.