当前位置:网站首页>Getting started with database connection pooling (c3p0, Druid)
Getting started with database connection pooling (c3p0, Druid)
2022-06-22 19:00:00 【Share a drink none】
This article has participated in 「 New people's creation ceremony 」 Activities , Start the road of nuggets creation together .
Concept
The database connection pool is actually a container ( aggregate ), Container for database connection . When the system is initialized , The container is created , Some connection objects will be requested in the container , When the user comes to access the database , Get the connection object from the container , After the user visits , The connection object is returned to the container .
benefits
- Saving resource
- Efficient user access
Realization
Standard interface :DataSource javax.sql Under bag Method :
- Get the connection :
getConnection() - Return connection :
Connection.close(). If the connection object Connection It's taken from the connection pool , So called Connection.close() Method , The connection will no longer be closed . But return the connection
Generally we don't realize it , There are database vendors to implement
- C3P0: Database connection pool technology
- Druid: Database connection pool implementation technology , Provided by Alibaba
C3P0: Database connection pool technology
step :
- Import jar package ( Two )
<!--c3p0 Connection pool -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>mchange-commons-java</artifactId>
<version>0.2.19</version>
</dependency>
- Define configuration file :
name : c3p0.properties perhaps c3p0-config.xml route : Put the document directly in resource Under the directory . The configuration file case is as follows :
<c3p0-config>
<!-- Use the default configuration to read connection pool objects -->
<default-config>
<!-- Connection parameters -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db4</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- Connection pool parameters -->
<!-- Number of connections to initialize the request -->
<property name="initialPoolSize">5</property>
<!-- Maximum number of connections -->
<property name="maxPoolSize">10</property>
<!-- Timeout time -->
<property name="checkoutTimeout">3000</property>
</default-config>
<named-config name="otherc3p0">
<!-- Connection parameters -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db3</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- Connection pool parameters -->
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">8</property>
<property name="checkoutTimeout">1000</property>
</named-config>
</c3p0-config>
- Create core objects Database connection pool object ComboPooledDataSource
- Get the connection : getConnection
Code :
public static void main(String[] args) throws SQLException {
//1. Create database connection pool object , Use default configuration
DataSource ds = new ComboPooledDataSource();
//2. Get the connection
for (int i = 1; i <= 11; i++) {
Connection conn = ds.getConnection();
System.out.println(i + ":" + conn);
if (i == 5) {
conn.close();// Return connections to the connection pool
}
}
//testNamedConfig();
}
public static void testNamedConfig() throws SQLException {
// 1.1 obtain DataSource, Configure with the specified name
DataSource ds = new ComboPooledDataSource("otherc3p0");
//2. Get the connection
for (int i = 1; i <= 10; i++) {
Connection conn = ds.getConnection();
System.out.println(i + ":" + conn);
}
}
Druid: Database connection pool implementation technology , Provided by Alibaba
step
- Import jar package
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
- Define configuration file :
yes properties Formal You can call it anything , It can be placed in any directory 2. Load profile .Properties 2. Get database connection pool object : From the factory DruidDataSourceFactory 2. Get the connection :getConnection Code :
//3. Load profile ( stay resource Under the table of contents )
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//4. Get connection pool object
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
//5. Get the connection
Connection conn = ds.getConnection();
Define tool classes
- Define a class JDBCUtils
- Provide static code block loading configuration file , Initialize connection pool object
- Provide methods
- Get the connection method : Get the connection through the database connection pool
- Release resources
- How to get the connection pool
Code :
public class JDBCUtils {
//1. Define member variables DataSource
private static DataSource ds ;
static{
try {
//1. Load profile
Properties pro = new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//2. obtain DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/** * Get the connection */
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/** * Release resources */
public static void close(Statement stmt,Connection conn){
/* if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close();// Return connection } catch (SQLException e) { e.printStackTrace(); } }*/
close(null,stmt,conn);
}
public static void close(ResultSet rs , Statement stmt, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();// Return connection
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/** * Get connection pool method */
public static DataSource getDataSource(){
return ds;
}
}
This is the end of this article ,
If you have any harvest, you are welcome to like, collect and pay attention to ️, Your encouragement is my biggest motivation .
If you have any wrong questions, you are welcome to point out .
Home page : Share a cup of no blog summary
Keep loving , Go to the next mountain and sea .
边栏推荐
- Makefile将某一部分文件不编译
- postman学习
- 2022年G2电站锅炉司炉题库及在线模拟考试
- Huawei cloud "digital intelligence" operation and maintenance
- Azkaban startup error 2022/06/20 21:39:27.726 +0800 error [stdouterrredirect] [azkaban] exception in thread "m
- 2022年T电梯修理复训题库及答案
- Alibaba cloud cannot find the account security group id problem during the account transfer
- 如何持续突破性能表现? | DX研发模式
- 2022焊工(初级)特种作业证考试题库模拟考试平台操作
- 面试MySQL
猜你喜欢

Cookie加密3+RPC解法

2022年G2电站锅炉司炉题库及在线模拟考试
Redis usage scenario sharing (project practice)

Babbitt | yuancosmos daily must read: it is said that Tencent has established XR department, and yuancosmos sector has risen again. Many securities companies have issued reports to pay attention to th

Beijing restorer's half moon: how to rekindle the fireworks in store management

I became a big enemy when I bought wanghong ice cream

Five practical tips for power Bi (complimentary books at the end of the article)

腾讯云国际版云服务器欠费说明

In May, 2022, China's game manufacturers and applications went to sea, with top 30 revenue in EMEA region

vs code突然无法进行代码跳转
随机推荐
腾讯云国际版云服务器欠费说明
零基础学编程/学逆向/过检测(frida实战)
排序---
[OWT] OWT client native P2P E2E test vs2017 build
DBMS in Oracle_ output. put_ Example of line usage
【工具】pip和conda的相關使用
Game NFT Market: opensea's most easily cut cake
When do project managers particularly want to escape from work?
@Lucky user of "Qilu Duojiao", Shandong 5A scenic spot calls you to visit the park for free!
2022年T电梯修理复训题库及答案
巴比特 | 元宇宙每日必读:传腾讯成立XR部门,元宇宙板块再次上涨,多家券商发报告关注虚拟人的投资机会...
Filebeat collects log data and transfers it to redis. Different es indexes are created based on log fields through logstash
Azkaban startup error 2022/06/20 21:39:27.726 +0800 error [stdouterrredirect] [azkaban] exception in thread "m
Makefile将某一部分文件不编译
How does flynk MySQL CDC guarantee the server_ Is the ID globally unique?
Set of redis data structure
C sqlsugar, hisql, FreeSQL ORM framework omni-directional performance test comparison sqlserver
Exness sorted out three problems to be solved in Musk's acquisition of Twitter
A course for New Oriental transformation bilingual live broadcast to bring goods to the project manager
如何在 FlowUs和Notion 等笔记软件中进行任务管理?