黄色网址大全免费-黄色网址你懂得-黄色网址你懂的-黄色网址有那些-免费超爽视频-免费大片黄国产在线观看

專注Java教育14年 全國(guó)咨詢/投訴熱線:400-8080-105
動(dòng)力節(jié)點(diǎn)LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁(yè) 學(xué)習(xí)攻略 Java學(xué)習(xí) Java連接池詳解

Java連接池詳解

更新時(shí)間:2022-11-17 11:15:54 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽2385次

連接池是指連接對(duì)象池。連接池基于對(duì)象池設(shè)計(jì)模式。當(dāng)創(chuàng)建新對(duì)象的成本(時(shí)間和資源,如 CPU、網(wǎng)絡(luò)和 IO)較高時(shí),使用對(duì)象池設(shè)計(jì)模式。根據(jù)對(duì)象池設(shè)計(jì)模式,應(yīng)用程序預(yù)先創(chuàng)建一個(gè)對(duì)象并將它們放置在池或容器中。每當(dāng)我們的應(yīng)用程序需要此類對(duì)象時(shí),它都會(huì)從池中獲取它們,而不是創(chuàng)建一個(gè)新對(duì)象。

使用連接池策略的應(yīng)用程序已經(jīng)具有可以重用的數(shù)據(jù)庫(kù)連接對(duì)象。所以,當(dāng)需要與數(shù)據(jù)庫(kù)進(jìn)行交互時(shí),應(yīng)用程序從Pool中獲取連接實(shí)例。連接池提高了與數(shù)據(jù)庫(kù)交互的應(yīng)用程序性能。

Java 應(yīng)用程序中的連接池

讓我們看看下面的庫(kù):

Apache Commons DBCP 2

光CP

C3P0

讓我們一個(gè)一個(gè)地看下面的例子。出于演示目的,我們將使用 MySQL 數(shù)據(jù)庫(kù)和 Eclipse IDE。我們還將使用 JDK 1.8 創(chuàng)建基于 Maven 的簡(jiǎn)單 Java 項(xiàng)目。

數(shù)據(jù)庫(kù)腳本

create database empdb;
use empdb;
create table tblemployee(
                    empId integer AUTO_INCREMENT primary key,
                    empName varchar(64),
                    dob date,
                    designation varchar(64)
);
insert into  tblemployee(empId,empName,dob,designation) values (default,'Adam','1998-08-15','Manager');
insert into  tblemployee(empId,empName,dob,designation) values (default,'Smith','2001-01-11','Clerk');
insert into  tblemployee(empId,empName,dob,designation) values (default,'James','1996-03-13','Officer');

示例項(xiàng)目

按照以下步驟創(chuàng)建新項(xiàng)目。

打開(kāi) Eclipse 集成開(kāi)發(fā)環(huán)境。

單擊文件菜單并選擇新建 -> Maven 項(xiàng)目

將顯示以下屏幕。選擇創(chuàng)建一個(gè)簡(jiǎn)單的項(xiàng)目選項(xiàng)并單擊下一步按鈕。

輸入任何組 ID、工件 ID、名稱和描述。

單擊完成按鈕。

在 MySQL 的 pom.xml 中添加以下依賴項(xiàng)。

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.49</version>
</dependency>

右鍵單擊項(xiàng)目,選擇 Maven -> 更新項(xiàng)目 -> 確定。它將下載所有依賴項(xiàng)。

Apache DBCP 2

DBCP 來(lái)自 Apache Common Project。DBCP 2.7 需要 Java 8。要使用 DBCP 2,您需要在項(xiàng)目中添加以下依賴項(xiàng)。

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-dbcp2</artifactId>
	<version>2.7.0</version>
</dependency>

Apache DBCP 2.0 提供了兩種類型的數(shù)據(jù)源(BasicDataSource 和 PoolingDataSource)。

BasicDataSource:顧名思義,它很簡(jiǎn)單,適用于大多數(shù)常見(jiàn)的用例。它在內(nèi)部為我們創(chuàng)建了 PoolingDataSource。

讓我們看看以下初始化連接池的步驟。

創(chuàng)建 BasicDataSource 的實(shí)例

指定 JDBC Url、數(shù)據(jù)庫(kù)用戶名和密碼

指定最小空閑連接數(shù)(Minimum number of connections that need to remain in the pool anytime)

指定最大空閑連接數(shù)(Maximum number of Idle connection in the pool)

指定最大連接總數(shù)。

package com.journaldev.example;
/**
 * Java JDBC Connection pool using Apache commons DBCP2 example program
 * 
 * @author pankaj
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.dbcp2.BasicDataSource;
public class DBCP2Demo {
	private static BasicDataSource dataSource = null;
	static {
		dataSource = new BasicDataSource();
		dataSource.setUrl("jdbc:mysql://localhost:3306/empdb?useSSL=false");
		dataSource.setUsername("root");
		dataSource.setPassword("root");
		dataSource.setMinIdle(5);
		dataSource.setMaxIdle(10);
		dataSource.setMaxTotal(25);
	}
public static void main(String[] args) throws SQLException {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = dataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery("select * from tblemployee");
			while (resultSet.next()) {
				System.out.println("empId:" + resultSet.getInt("empId"));
				System.out.println("empName:" + resultSet.getString("empName"));
				System.out.println("dob:" + resultSet.getDate("dob"));
				System.out.println("designation:" + resultSet.getString("designation"));
			}
		} finally {
			resultSet.close();
			statement.close();
			connection.close();
		}
	}
}

輸出:

empId:1
empName:Adam
dob:1998-08-15
designation:Manager
empId:2
empName:Smith
dob:2001-01-11
designation:Clerk
empId:3
empName:James
dob:1996-03-13
designation:Officer

PoolingDataSource:它提供了更多的靈活性。您只需要更改創(chuàng)建數(shù)據(jù)源的代碼。其余代碼將保持不變。

讓我們看一下初始化連接池的以下步驟:

使用 JDBC URL 創(chuàng)建 ConnectionFactory 的實(shí)例。

使用在步驟 1 中創(chuàng)建的 ConnectionFactory 實(shí)例創(chuàng)建 PoolableConnectionFactory 實(shí)例

創(chuàng)建 GenericObjectPoolConfig 的實(shí)例并設(shè)置最大空閑、最小空閑和最大連接屬性

現(xiàn)在使用在步驟 2 和步驟 3 中創(chuàng)建的實(shí)例初始化 ObjectPool

現(xiàn)在將池設(shè)置為 PoolableConnectionFactory 的實(shí)例

最后,初始化DataSource的一個(gè)實(shí)例

private static DataSource dataSource = null;
	static {
		Properties properties = new Properties();
		properties.setProperty("user", "root");
		properties.setProperty("password", "root");
		ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:mysql://localhost:3306/empdb",
				properties);
		PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
		GenericObjectPoolConfig<PoolableConnection> config = new GenericObjectPoolConfig<>();
		config.setMaxTotal(25);
		config.setMaxIdle(10);
		config.setMinIdle(5);
		ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config);
		poolableConnectionFactory.setPool(connectionPool);
		dataSource = new PoolingDataSource<>(connectionPool);
	}

HikariCP

HikariCP 快速、可靠且簡(jiǎn)單。它是連接池的首選解決方案之一。像 Spring Boot 2.x 這樣的框架使用它作為默認(rèn)的連接管理器。

要使用 HikariCP,請(qǐng)?jiān)谖覀冺?xiàng)目的 pom.xml 中添加以下依賴項(xiàng)。

<dependency>
	<groupId>com.zaxxer</groupId>
	<artifactId>HikariCP</artifactId>
	<version>3.4.5</version>
</dependency>

HikariCP 配置:

我們可以使用基于 Java 的配置,如下面的示例程序所示,或者我們可以使用屬性文件來(lái)配置 HikariCP。讓我們看看下面的屬性。

idleTimeout:連接對(duì)象可以在池中保持空閑狀態(tài)的時(shí)間(以毫秒為單位)。它適用于minimumIdle和maximumPoolSize屬性。在指定的時(shí)間后連接對(duì)象將被釋放。

connectionTimeout:客戶端等待來(lái)自池的連接對(duì)象的時(shí)間(以毫秒為單位)。如果達(dá)到時(shí)間限制,則將拋出 SQL 異常。

autoCommit : 我們可以指定 true 或 false ,如果設(shè)置為 true 那么它會(huì)自動(dòng)提交你執(zhí)行的每條 SQL 語(yǔ)句,如果設(shè)置為 false 那么我們需要手動(dòng)提交 SQL 語(yǔ)句

cachePrepStmts:為 Prepare Statement 啟用緩存

minimumIdle:任何時(shí)候連接池中需要保留的最少連接對(duì)象數(shù)。

maximumPoolSize:可以保留在池中的最大連接數(shù)。

package com.journaldev.example;
/**
 * Java JDBC Connection pool using HikariCP example program
 * 
 * @author pankaj
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
public class HikariCPDemo {
	private static HikariDataSource dataSource = null;
	static {
		HikariConfig config = new HikariConfig();
		config.setJdbcUrl("jdbc:mysql://localhost:3306/empdb");
		config.setUsername("root");
		config.setPassword("root");
		config.addDataSourceProperty("minimumIdle", "5");
		config.addDataSourceProperty("maximumPoolSize", "25");
		dataSource = new HikariDataSource(config);
	}
	public static void main(String[] args) throws SQLException {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = dataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery("select * from tblemployee");
			while (resultSet.next()) {
				System.out.println("empId:" + resultSet.getInt("empId"));
				System.out.println("empName:" + resultSet.getString("empName"));
				System.out.println("dob:" + resultSet.getDate("dob"));
				System.out.println("designation:" + resultSet.getString("designation"));
			}
		} finally {
			resultSet.close();
			statement.close();
			connection.close();
		}
	}
}

輸出:

empId:1
empName:Adam
dob:1998-08-15
designation:Manager
empId:2
empName:Smith
dob:2001-01-11
designation:Clerk
empId:3
empName:James
dob:1996-03-13
designation:Officer

C3P0

通常,它與 Hibernate 一起使用。要使用 C3P0,我們需要在項(xiàng)目中添加以下依賴。

<dependency>
	<groupId>com.mchange</groupId>
	<artifactId>c3p0</artifactId>
	<version>0.9.5.5</version>
</dependency>

我們可以使用 C3P0 配置以下屬性。

driverClass:首選 Jdbc 驅(qū)動(dòng)程序

jdbcUrl:數(shù)據(jù)庫(kù)的 JDBC Url。

initialPoolSize:?jiǎn)?dòng)時(shí)在池中創(chuàng)建的連接數(shù)。

acquireIncrement:當(dāng)前大小不夠時(shí)需要?jiǎng)?chuàng)建的新連接數(shù)。

maxIdleTime:連接可以保留在池中而不被使用的秒數(shù)。

maxPoolSize:可以保留在 Pool 中的最大連接數(shù)。

minPoolSize:任何時(shí)候Pool中需要保留的最小連接對(duì)象數(shù)。

package com.journaldev.example;
/**
 * Java JDBC Connection pool using C3PO example program
 * 
 * @author pankaj
 */
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Demo {
	static ComboPooledDataSource comboPooledDataSource = null;
	static {
		comboPooledDataSource = new ComboPooledDataSource();
		comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/empdb?useSSL=false");
		comboPooledDataSource.setUser("root");
		comboPooledDataSource.setPassword("root");
		comboPooledDataSource.setMinPoolSize(3);
		comboPooledDataSource.setAcquireIncrement(3);
		comboPooledDataSource.setMaxPoolSize(30);
	}
public static void main(String[] args) throws SQLException {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = comboPooledDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery("select * from tblemployee");
			while (resultSet.next()) {
				System.out.println("empId:" + resultSet.getInt("empId"));
				System.out.println("empName:" + resultSet.getString("empName"));
				System.out.println("dob:" + resultSet.getDate("dob"));
				System.out.println("designation:" + resultSet.getString("designation"));
			}
		} finally {
			resultSet.close();
			statement.close();
			connection.close();
		}
	}
}

輸出:

Aug 29, 2020 8:59:05 PM com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource 
INFO: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, dataSourceName -> 1hge9kqacgbp7hjpftse6|77a567e1, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> null, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 1hge9kqacgbp7hjpftse6|77a567e1, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/empdb?useSSL=false, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 30, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
empId:1
empName:Adam
dob:1998-08-15
designation:Manager
empId:2
empName:Smith
dob:2001-01-11
designation:Clerk
empId:3
empName:James
dob:1996-03-13
designation:Officer

 

提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)

免費(fèi)課程推薦 >>
技術(shù)文檔推薦 >>
主站蜘蛛池模板: 免费视频18 | 亚洲黄色在线视频 | 日韩影院在线观看 | 欧美色碰碰碰免费观看长视频 | 国产成人a毛片在线 | 成人网网址 | 91精品国产91热久久p | 中文字幕日韩精品在线 | 孕交videos小孕妇xx中文 | 国产午夜精品久久理论片小说 | 手机在线资源 | 欧美精品专区免费观看 | 久久精品观看影院2828 | 香蕉黄色片 | 第一页在线 | 国产乱码精品一区二区三区网页版 | 午夜影院日韩 | 天天干天天爽 | 91在线视频免费播放 | 国产99在线播放免费 | 色综合久久综合网 | 伊人精品影院一本到欧美 | 亚洲一区二区三区在线观看蜜桃 | 日本黄色片在线播放 | 中国女人free性hd国语 | 男女羞羞视频 | 天天摸夜夜添夜夜添国产 | 日韩一级在线播放 | 日韩久久影院 | 噜噜色综合噜噜色噜噜色 | 中文字幕一区二区三区乱码 | 亚洲欧美国产一区二区三区 | 欧美日韩亚洲第一页 | 国产精品福利在线观看秒播 | 国产在线观看色 | 欧美三级一区二区 | 国产成人亚洲综合 | 久久国产高清波多野结衣 | 美女视频黄的免费视频网页 | 国产亚洲欧美一区二区 | 免费视频黄 |