c3p0连接池的配置和简单使用
背景
?一般我們在項目中操作數據庫時,都是每次需要操作數據庫就建立一個連接,操作完成后釋放連接。因為jdbc沒有保持連接的能力,一旦超過一定時間沒有使用(大約幾百毫秒),連接就會被自動釋放掉。而每次新建連接都需要140毫秒左右的時間,所以耗費時間比較多。若使用C3P0連接池來池化連接,隨時取用,則平均每次取用只需要10-20毫秒。這在高并發隨機訪問數據庫的時候對效率的提升有很大幫助。
??? C3P0連接池會根據你的配置來初始化N個數據庫連接,空閑T時間后連接過期又會自動新建K個連接使得連接池總有空閑的數據庫連接等待被取用。我們只需通過dataSourse.getConnection()即可從線程池中取用一個已經連接好的空閑連接,執行數據庫操作。然后“斷開”(放回)這個連接,把這個連接的使用權放回連接池。真正的數據庫連接的創建與釋放是由C3P0在后臺自動完成的,我們花的只是取用與釋放占用權的時間。全程耗時10+毫秒,比原來提高了幾十倍
?
下載
c3p0下載地址:https://sourceforge.net/projects/c3p0/files/latest/download?source=files? ?下載完成后,將解壓出來有3個jar包:
? ? ? ? ? ? ? ? ? ? ? ?
將這三個jar包導入項目中,?在src目錄下新建一個名叫? c3p0-config.xml? 的文件,注意,必須是這個文件名。?
?
配置?
c3p0-config.xml的示例代碼如下圖所示:
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <!-- 默認配置 --> <default-config> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <!-- 配置oracle連接池 --> <named-config name="oracle"> <property name="driverClass">oracle.jdbc.driver.OracleDriver</property> <property name="jdbcUrl">jdbc:oracle:thin:@192.168.1.138:1521:ecology</property> <property name="user">test1028</property> <property name="password">test1028</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </named-config> <!--配置連接池mysql--><named-config name="mysql"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://192.168.1.123:3306/CoupleSpace</property> <property name="user">root</property> <property name="password">root</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </named-config> <!-- 配置其他連接池--> </c3p0-config>?更細致的配置說明如下圖所示:
<!--acquireIncrement:鏈接用完了自動增量3個。 --><property name="acquireIncrement">3</property><!--acquireRetryAttempts:鏈接失敗后重新試30次。--><property name="acquireRetryAttempts">30</property><!--acquireRetryDelay;兩次連接中間隔1000毫秒。 --><property name="acquireRetryDelay">1000</property><!--autoCommitOnClose:連接關閉時默認將所有未提交的操作回滾。 --><property name="autoCommitOnClose">false</property><!--automaticTestTable:c3p0測試表,沒什么用。--><property name="automaticTestTable">Test</property><!--breakAfterAcquireFailure:出錯時不把正在提交的數據拋棄。--><property name="breakAfterAcquireFailure">false</property><!--checkoutTimeout:100毫秒后如果sql數據沒有執行完將會報錯,如果設置成0,那么將會無限的等待。 --> <property name="checkoutTimeout">100</property><!--connectionTesterClassName:通過實現ConnectionTester或QueryConnectionTester的類來測試連接。類名需制定全路徑。Default: com.mchange.v2.c3p0.impl.DefaultConnectionTester--><property name="connectionTesterClassName"></property><!--factoryClassLocation:指定c3p0 libraries的路徑,如果(通常都是這樣)在本地即可獲得那么無需設置,默認null即可。--><property name="factoryClassLocation">null</property><!--forceIgnoreUnresolvedTransactions:作者強烈建議不使用的一個屬性。--> <property name="forceIgnoreUnresolvedTransactions">false</property><!--idleConnectionTestPeriod:每60秒檢查所有連接池中的空閑連接。--> <property name="idleConnectionTestPeriod">60</property><!--initialPoolSize:初始化時獲取三個連接,取值應在minPoolSize與maxPoolSize之間。 --> <property name="initialPoolSize">3</property><!--maxIdleTime:最大空閑時間,60秒內未使用則連接被丟棄。若為0則永不丟棄。--><property name="maxIdleTime">60</property><!--maxPoolSize:連接池中保留的最大連接數。 --><property name="maxPoolSize">15</property><!--maxStatements:最大鏈接數。--><property name="maxStatements">100</property><!--maxStatementsPerConnection:定義了連接池內單個連接所擁有的最大緩存statements數。Default: 0 --><property name="maxStatementsPerConnection"></property><!--numHelperThreads:異步操作,提升性能通過多線程實現多個操作同時被執行。Default: 3--> <property name="numHelperThreads">3</property><!--overrideDefaultUser:當用戶調用getConnection()時使root用戶成為去獲取連接的用戶。主要用于連接池連接非c3p0的數據源時。Default: null--> <property name="overrideDefaultUser">root</property><!--overrideDefaultPassword:與overrideDefaultUser參數對應使用的一個參數。Default: null--><property name="overrideDefaultPassword">password</property><!--password:密碼。Default: null--> <property name="password"></property><!--preferredTestQuery:定義所有連接測試都執行的測試語句。在使用連接測試的情況下這個一顯著提高測試速度。注意: 測試的表必須在初始數據源的時候就存在。Default: null--><property name="preferredTestQuery">select id from test where id=1</property><!--propertyCycle:用戶修改系統配置參數執行前最多等待300秒。Default: 300 --> <property name="propertyCycle">300</property><!--testConnectionOnCheckout:因性能消耗大請只在需要的時候使用它。Default: false --><property name="testConnectionOnCheckout">false</property><!--testConnectionOnCheckin:如果設為true那么在取得連接的同時將校驗連接的有效性。Default: false --><property name="testConnectionOnCheckin">true</property><!--user:用戶名。Default: null--><property name="user">root</property><!--usesTraditionalReflectiveProxies:動態反射代理。Default: false--><property name="usesTraditionalReflectiveProxies">false</property>?
使用方式
新建一個c3p0的工具類,如下圖所示:
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.mchange.v2.c3p0.ComboPooledDataSource;public class C3P0Util { static ComboPooledDataSource dataSource = new ComboPooledDataSource("oracle");/*** 獲取數據庫連接* @return* @throws SQLException */public static Connection getConnection() throws SQLException{return dataSource.getConnection();}/*** 關閉數據庫連接* @throws SQLException */public static void closeConnection(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) throws SQLException{if (connection!=null && !connection.isClosed()) {connection.close();}if (preparedStatement!=null && !preparedStatement.isClosed()) {preparedStatement.close();}if (resultSet != null && !resultSet.isClosed()) {resultSet.close();}} }在jdbc中使用c3p0工具類獲得連接并查詢數據:
public ArrayList<Dept> queryDepts() throws SQLException{ArrayList<Dept> depts = new ArrayList<Dept>();try(Connection connection = C3P0Util.getConnection();PreparedStatement stmt=connection.prepareStatement("select * from ecology09171.bm");ResultSet rs=stmt.executeQuery();){while(rs.next()){Dept dept = new Dept();long id = rs.getLong("ID");String departmentName = rs.getString("DEPARTMENTNAME");long supDepID = rs.getLong("SUPDEPID");long subCompanyID1 = rs.getLong("SUBCOMPANYID1");String departmentMark = rs.getString("DEPARTMENTMARK");String canceled = rs.getString("CANCELED");dept.setID(id);dept.setSUPDEPID(supDepID);dept.setSUBCOMPANYID1(subCompanyID1);dept.setDEPARTMENTNAME(departmentName);dept.setDEPARTMENTMARK(departmentMark);dept.setCANCELED(canceled);depts.add(dept);}return depts;}}?
?
?
總結
以上是生活随笔為你收集整理的c3p0连接池的配置和简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 鲲鹏服务器php性能,对鲲鹏服务器的内存
- 下一篇: 使用ffmpeg 将mp4文件转化未hl