数据库连接池配置
-
安装阿里德鲁伊驱动(数据库连接池)和mysql驱动
-
配置德鲁伊数据连接池
package cn.edu.mju.project1.persiste.impl;
import com.alibaba.druid.pool.DruidDataSource;
import java.sql.Connection;
public class MySqlDbUtil {
private static DruidDataSource dataSource = null;
private static void initDataSource() throws Exception{
//连接池链接配置
if(dataSource == null){
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/band1?serverTimezone=Asia/Shanghai"); //数据库地址
dataSource.setUsername("root"); //数据库账号
dataSource.setPassword("konodioda2019"); //数据库密码
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); //加载mysql驱动包
//连接池维护配置
dataSource.setInitialSize(2); //初始连接数
dataSource.setMinIdle(2); //最小连接数
dataSource.setMaxActive(10); //最大连接数
dataSource.setMaxWait(20000); //最大响应时间
dataSource.setTimeBetweenEvictionRunsMillis(20000); //链接最大空闲时间
dataSource.setValidationQuery("select 'x'"); //向数据库请求数据防止被断开链接,类似ping
dataSource.setTestWhileIdle(true);
dataSource.setTestOnBorrow(true);
}
}
public static Connection getConnection() throws Exception{
initDataSource();
return dataSource.getConnection();
}
}
- 注意事项
- 配置url时需要设置时区serverTimezone=Asia/Shanghai
dataSource.setUrl("jdbc:mysql://localhost:3306/band1?serverTimezone=Asia/Shanghai");
- 高版本mysql驱动路径低版本驱动不一样
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");