问题引出
当我们java提供的最原始的链接数据库的时候,其中的步骤会比较繁琐,而且每次用到链接我们都需要重新创建,使用完之后关闭连接,这样不仅效率极低,而且耗时也会非常的长。如果成千上万的用户过来连接,这样我们就需要创建成千上万个连接,估计一般的服务器扛不住。
解决方案
创建连接池,当项目初始化的时候,我们新建立连接池,每次用户来访问的时候,我们从连接池中拿连接,用户用完之后,不要关闭连接,直接把连接归还到连接池中,这样就能解决以上问题。
实现步骤
C3P0连接池的使用,(要想连接池能够正常使用,必要的环境就是准备了jdbc环境,以为第三方连接池都是在这个基础上面拓展而来的,这也是基础。
jdbc需要导入的jar包
链接:https://pan.baidu.com/s/12y2-LqSOMC0eRU-LqlDU9g
提取码:kq8o
环境搭建之后,开始连接池工具类的创建:
第一步:导入C3P0的Jar包
链接:https://pan.baidu.com/s/17sRrQ9YNslMbdz_N-HRsYw
提取码:9qdu
第二步:
配置c3p0-config.xml文件,这里需要注意,c3p0的配置文件名是固定的,不能更改,而且需要放置到src资源文件目录下面。
<?xml version = "1.0" encoding = "utf-8" standalone = "yes"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/webDB?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf-8&rewriteBatchedStatements=true</property>
<property name="user">root</property>
<property name="password">root</property>
</default-config>
</c3p0-config>
第三步:工具类的编写
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 开源C3P0连接池工具类,用来获取连接池或者连接
*/
public class C3P0ConnPool {
//创建静态的c3p0连接池对象,只加载一次即可
private static DataSource c3p0DataSource = new ComboPooledDataSource();
//提供返回连接的方法
public static Connection getConnection() throws SQLException {
//返回连接
return c3p0DataSource.getConnection();
}
//提供返回连接池的方法
public static DataSource getDataSource(){
return c3p0DataSource;
}
}
三步完成,这样我们随时可以从C3P0工具类中获取连接池或者从连接池中拿连接了。
阿里Druid连接池的使用
第一步:
导入jar包
链接:https://pan.baidu.com/s/1qv3-I-h3394x4nBPe0jHJQ
提取码:6juf
第二步:
druid.properties属性配置文件,这里不是xml文件,文件名可以自取.
# 数据库连接参数
url=jdbc:mysql://localhost:3306/mydb2?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf-8&rewriteBatchedStatements=true
username=root
password=root
driverClassName=com.mysql.jdbc.Driver
# 连接池的参数
initialSize=10
maxActive=10
maxWait=2000
第三步:工具类编写
/**
* Druid阿里连接池工具,目前国内最好用的连接池之一,各方面功能,性能,拓展性都比较优越
*
*/
public class DruidConnPool {
//全局静态变量 druid连接池
private static DataSource druidDataSource;
//对连接池进行初始化
static {
try {
//创建属性集properties对象
Properties pps = new Properties();
//获取配置文件inputstream字节流对象
InputStream is = DruidConnPool.class.getClassLoader().getResourceAsStream("druid.properties");
//把配置文件加载进属性文件对象中
pps.load(is);
//创建druid连接池
druidDataSource = DruidDataSourceFactory.createDataSource(pps);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @return 从初始化druid连接池中返回一个连接给调用者
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return druidDataSource.getConnection();
}
/**
* 返回druid连接池给调用者
* @return
*/
public static DataSource getDruidDataSource(){
return druidDataSource;
}
}
手工…