当前位置:网站首页>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 .
边栏推荐
- Grafana 9 is officially released, which is easier to use and more cool!
- 使用完整功能模仿设计法
- Golang implements redis (10): local atomic transactions
- Pre training language model, Bert, roformer SIM, also known as simbertv2
- 中国移动手机用户缓慢增长,但努力争取高利润的5G套餐用户
- 阿里云过户找不到账号安全组ID问题
- [learn shell programming easily]-4. The difference between single quotation marks and double quotation marks, the operation of integer values, the definition of arrays in the shell and the detailed us
- Filebeat收集日志数据传输到Redis,通过Logstash来根据日志字段创建不同的ES索引
- Activity跳转到Fragment的方法(Intent)
- SystemVerilog(十二)-$unit声明空间
猜你喜欢

巴比特 | 元宇宙每日必读:传腾讯成立XR部门,元宇宙板块再次上涨,多家券商发报告关注虚拟人的投资机会...

链表4- 21 合并两个有序链表

第四届青年生命科学论坛 | 第一轮通知

Game NFT Market: opensea's most easily cut cake

SOA面向服务的架构

2022年5月中国游戏厂商及应用出海 EMEA 地区收入30强

Activity跳转到Fragment的方法(Intent)

阻碍华为5G手机的关键芯片取得突破,国产芯片已取得一成份额
Concepts and solutions of redis' cache penetration, cache avalanche and cache breakdown problems

牛客网:最小覆盖子串
随机推荐
Does CDC 2.2.1 monitoring sqlserver not support monitoring multiple databases?
c# sqlsugar,hisql,freesql orm框架全方位性能测试对比之sqlserver
exness整理马斯克收购推特需要解决三个问题
Modèle de langage de pré - formation, Bert, roformer Sim aussi connu sous le nom de simbertv2
2022年G2电站锅炉司炉题库及在线模拟考试
China's two meteorological "new stars" data products are shared with global users
Redis中的布隆过滤器与布谷鸟过滤器,你了解多少?
Correct method of converting Inkscape into DXF file SVG exporting DXF file
Live broadcast Preview - 12 first-class Chinese scholars open ICLR 2022
[轻松学会shell编程]-4、单引号和双引号的区别、整形数值的运算、shell中数组定义和sed的详细用法
Database industry analysis: from the global IT industry trend to the development of domestic databases
chrome突然无法复制粘贴了
Nuxt - create nuxt app
数组模拟栈
线程池:ThreadPoolExcutor源码阅读
【工具】pip和conda的相关使用
阻碍华为5G手机的关键芯片取得突破,国产芯片已取得一成份额
Mysql如何删除数据库表中的某一列
Sort---
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