首先导入Jar包,该资源我已经给出了,本文章的绑定资源
然后将原有的jdbc获取连接改成如下方式:
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/** 数据库连接工具(使用Druid连接池) */
public class JdbcUtils {
private static DruidDataSource dataSource;
static {
try {
// 配置Druid连接池参数
Properties properties = new Properties();
properties.put("driverClassName", "com.mysql.cj.jdbc.Driver");
properties.put("url", "jdbc:mysql://localhost:3306/app_logistics?serverTimezone=GMT%2B8&characterEncoding=utf-8&allowPublicKeyRetrieval=true&useSSL=false");
properties.put("username", "app_logistics"); // 修改为你的用户名
properties.put("password", "app_logistics"); // 修改为你的密码
// 连接池优化参数(根据需求调整)
properties.put("initialSize", "5"); // 初始连接数
properties.put("minIdle", "5"); // 最小空闲连接
properties.put("maxActive", "20"); // 最大活跃连接
properties.put("maxWait", "30000"); // 获取连接超时时间(毫秒)
properties.put("timeBetweenEvictionRunsMillis", "60000"); // 检查间隔
properties.put("minEvictableIdleTimeMillis", "300000"); // 最小空闲时间
properties.put("validationQuery", "SELECT 1"); // 心跳检测SQL
properties.put("testWhileIdle", "true");
properties.put("testOnBorrow", "false");
properties.put("testOnReturn", "false");
// 初始化连接池
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException("Druid连接池初始化失败", e);
}
}
/** 从连接池获取连接 */
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("获取数据库连接失败", e);
}
}
/** 归还连接(实际是放回连接池)*/
public static void closeConnection(Connection conn) {
if (conn != null) {
try {
conn.close(); // 实际不会关闭连接,而是归还给连接池
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}