Java 數(shù)據(jù)庫連接池 DBCP 的介紹
DBCP
(Database connection pooling) 是 Apache 旗下 Commons
項目下的一個子項目,提供連接池功能;本文主要介紹 DBCP 的基本使用,文中使用到的軟件版本:Java 1.8.0_191、DBCP 2.9.0、Spring Boot
2.3.12.RELEASE。
1、配置參數(shù)
參數(shù) | 描述 |
username | 用戶名 |
password | 密碼 |
url | 連接 url |
driverClassName | 驅(qū)動名稱 |
connectionProperties |
連接屬性,格式為: [propertyName=property;]* |
參數(shù) | 默認值 | 描述 |
?defaultAutoCommit | ?驅(qū)動的默認值 | ?是否自動提交 |
?defaultReadOnly | ?驅(qū)動的默認值 | ?是否只讀 |
?defaultTransactionIsolation | ?驅(qū)動的默認值 |
默認的事務(wù)隔離級別 |
?defaultCatalog | ? |
默認的 catalog。(目錄,類似于模式名,但比模式名更加抽象; |
?cacheState | ?true | ?是否緩存狀態(tài)信息 |
?defaultQueryTimeout | ?null | ?默認查詢時間 |
?enableAutoCommitOnReturn | ?true | ?連接歸還到池時,是否設(shè)置為自動提交 |
?rollbackOnReturn | ?true |
如果設(shè)置為 true,則連接歸還到連接池時, |
?參數(shù) | 默認值? | 描述 |
?initialSize | ?0 | 初始連接數(shù) |
?maxTotal | ?8 | 最大連接數(shù);負數(shù)表示沒有限制 |
?maxIdle | ?8 | 最大空閑連接數(shù),多余的空閑連接將被釋放;負數(shù)表示沒有限制 |
?minIdle | ?0 | 最小空閑連接數(shù),如果不足則新的空閑連接將被創(chuàng)建。 |
?maxWaitMillis | ?indefinitely | 從連接池獲取連接,最大等待時間,超過該時間將拋出異常;-1 表示無限期 |
參數(shù) | 默認值 | 描述 |
validationQuery | ? |
連接池返回連接給調(diào)用者前用來校驗的查詢sql。 |
validationQueryTimeout | no timeout | 驗證查詢超時時間(秒)。如果設(shè)置為正數(shù),那么通過 setQueryTimeOut()方法來設(shè)置查詢的超時時間。 |
testOnCreate | false | 連接創(chuàng)建后,是否驗證有效性 |
testOnBorrow | true | 從連接池獲取連接時,是否驗證有效性 |
testOnReturn | false | 連接返回連接池時,是否驗證有效性 |
testWhileIdle | false | 連接空閑時,是否驗證有效性;如果驗證失敗,則丟棄該連接。 |
timeBetweenEvictionRunsMillis | -1 | 校驗空閑連接的時間周期,非正表示不驗證 |
numTestsPerEvictionRun | 3 | 每次校驗空閑連接的個數(shù) |
minEvictableIdleTimeMillis | 1000 * 60 * 30 | 空閑連接至少多長時間后,才會被校驗 |
softMinEvictableIdleTimeMillis | -1 | 空閑連接至少多長時間后,才會被校驗;還需滿足"空閑連接數(shù)>=minIdle" |
maxConnLifetimeMillis | -1 | 連接存活的最大時間;如果設(shè)置為非正數(shù),則存活時間是無限的 |
logExpiredConnections | true | 過期的連接被連接池關(guān)閉時,是否寫日志 |
connectionInitSqls | null | 連接第一次創(chuàng)建時,執(zhí)行的初始化 SQL |
lifo | true | true 表示獲取連接時將返回最后返還連接池的連接(后進先出);false,則相反(先進先出)。 |
參數(shù) | 默認值 | 描述 |
poolPreparedStatements | false | 預(yù)編譯語句是否池化 |
maxOpenPreparedStatements | unlimited | 最大打開的預(yù)處理語句,負數(shù)表示沒有限制 |
參數(shù) | 默認值 | 描述 |
accessToUnderlyingConnectionAllowed | false | 是否允許訪問底層連接 |
如果允許,可以使用下面的代碼來訪問底層連接:
Connection conn = ds.getConnection(); Connection dconn = ((DelegatingConnection) conn).getInnermostDelegate(); ... conn.close()
參數(shù) | 默認值 | 描述 |
removeAbandonedOnMaintenance removeAbandonedOnBorrow |
?false |
是否刪除泄露的連接;如果超過一個活動連接未使用的時間超過 removeAbandonedTimeout,則是一個泄露的連接。 |
removeAbandonedTimeout | ?300 | ?連接泄露的超時時間(秒) |
logAbandoned | false | ?連接刪除時是否打印堆棧信息 |
abandonedUsageTracking | false | 如果設(shè)置為 true,數(shù)據(jù)庫連接每執(zhí)行一個方法都會打印堆棧信息 |
參數(shù) | 默認值 | 描述 |
fastFailValidation | false |
是否快速失敗驗證;如果設(shè)置為 true,當發(fā)生致命異常時,不再執(zhí)行 isValid(),也不去執(zhí)行驗證查詢語句。致命的異常碼有: |
disconnectionSqlCodes | null | 自定義異常代碼 |
jmxName | ? | 注冊連接池的 jmx 名稱 |
詳細的配置說明可參考官網(wǎng)文檔:http://commons.apache.org/proper/commons-dbcp/configuration.html
。
2、使用
2.1、直接使用
2.1.1、引入依賴
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.9.0</version> </dependency>
2.1.2、使用例子
package com.abc.demo.general.dbpool; import org.apache.commons.dbcp2.BasicDataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBCPCase { public static void main(String[] args) { BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setUrl("jdbc:mysql://10.40.9.11:3306/mydb?useUnicode=true&characterEncoding=UTF-8"); basicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); basicDataSource.setUsername("root"); basicDataSource.setPassword("123456"); basicDataSource.setMaxTotal(20); basicDataSource.setMinIdle(5); Connection connection = null; Statement st = null; ResultSet rs = null; try { connection = basicDataSource.getConnection(); st = connection.createStatement(); rs = st.executeQuery("select version()"); if (rs.next()) { System.out.println(rs.getString(1)); } } catch (SQLException e) { e.printStackTrace(); } finally { close(connection); } try { //實際使用中一般是在應(yīng)用啟動時初始化數(shù)據(jù)源,應(yīng)用從數(shù)據(jù)源中獲取連接;并不會關(guān)閉數(shù)據(jù)源。 basicDataSource.close(); } catch (SQLException e) { e.printStackTrace(); } } private static void close(Connection connection) { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
2.2、在 SpringBoot 中使用
2.2.1、引入依賴
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.12.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies>
2.2.2、單數(shù)據(jù)源
application.yml 配置:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://10.40.9.11:3306/myDb?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 type: org.apache.commons.dbcp2.BasicDataSource dbcp2: max-total: 20 max-idle: 5
使用:
@Autowired private DataSource dataSource;
2.2.3、多數(shù)據(jù)源
application.yml 配置:
spring: datasource: dbcp2: db1: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://10.40.9.11:3306/myDb?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 max-total: 20 max-idle: 5 db2: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://10.40.9.12:3306/myDb?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 max-total: 20 max-idle: 5
數(shù)據(jù)源配置類:
package com.abc.demo.config; import org.apache.commons.dbcp2.BasicDataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class DataSourceConfig { @Bean("dataSource1") @ConfigurationProperties(prefix = "spring.datasource.dbcp2.db1") public DataSource dataSource1() { return DataSourceBuilder.create().type(BasicDataSource.class).build(); } @Bean("dataSource2") @ConfigurationProperties(prefix = "spring.datasource.dbcp2.db2") public DataSource dataSource2() { return DataSourceBuilder.create().type(BasicDataSource.class).build(); } }
使用:
@Autowired @Qualifier("dataSource1") private DataSource dataSource1; @Autowired @Qualifier("dataSource2") private DataSource dataSource2;
到此這篇關(guān)于 Java 數(shù)據(jù)庫連接池 DBCP 的介紹的文章就介紹到這了,更多相關(guān) Java? 連接池 DBCP內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JAVA實現(xiàn) springMVC方式的微信接入、實現(xiàn)消息自動回復(fù)實例
本篇文章主要介紹了JAVA實現(xiàn) springMVC方式的微信接入、實現(xiàn)消息自動回復(fù),這里整理了詳細的代碼,有需要的小伙伴可以參考下。2016-12-12類似Object監(jiān)視器方法的Condition接口(詳解)
下面小編就為大家?guī)硪黄愃芆bject監(jiān)視器方法的Condition接口(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05spring boot下 500 404 錯誤頁面處理的方法
本篇文章主要介紹了spring boot下 500 404 錯誤頁面處理的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04Spring Boot 2.0.0 終于正式發(fā)布-重大修訂版本
北京時間 2018 年 3 月 1 日早上,如約發(fā)布的 Spring Boot 2.0 在同步至 Maven 倉庫時出現(xiàn)問題,導(dǎo)致在 GitHub 上發(fā)布的 v2.0.0.RELEASE 被撤回2018-03-03